0

I have a text string as follows:

$input = "Lorem ipsum dolor sit amet, consectetur adipiscing add_filter('hello_text', 'sample'); elit. Sed vitae magna vel add_filter('goodbye_text', 'sample'); neque tincidunt.";

I need to search the $input string for "add_filter('***'" and get the *** text. If the string contains multiple different *** strings, I need to get them as well and save them to an array.

So the $input string above would generate: array('hello_text','goodbye_text')

I think I can use stripos () but I'm not sure how I would find this text pattern, as the *** text will be different every time.

2
  • 1
    Use a regular expression? Commented Dec 15, 2020 at 1:25
  • I find your minimal reproducible example to be Unclear. Commented May 29, 2024 at 20:48

2 Answers 2

2

This is based on dekameron's answer but makes the regular expression more generic.

<?php

$input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit add_filter('hello_text', 'sample'). Sed vitae magna add_filter('goodbye_text', 'sample') vel neque tincidunt.";

preg_match_all( "/add_filter\s*?\(\s*?'(.+?)'/ui", $input, $matches );

print_r($matches[1]);

Hook names are not restricted to just basic characters such as letters, numbers, underscore, etc. (Advanced Custom Fields is one plugin that uses forward slashes in the hook names). This regular expression will handle generic hook names (however, it won't handle escaped single quotes). Additionally, this will handle cases where the spacing between the "add_function", the opening paren, and the hook argument changes.

Sign up to request clarification or add additional context in comments.

3 Comments

Worked perfectly. Thanks! Also, I didn't realize hook names can have slashes etc. in them! Now I have to learn what that regular expression is doing...
@harvey, I suggest using regex101.com to test and examine regular expressions, regex101.com/r/NGBWah/1
Thanks I'll check that out!
1
<?php

function find_filters($string)
{
    if (!preg_match_all("|add_filter\('([a-z0-9_]+)'|ui", $string, $matches)) {
        return [];
    }

    return array_unique($matches[1]);
}

$input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit add_filter('hellotext', 'sample'). Sed vitae magna add_filter('goodbye_text', 'sample') vel neque tincidunt.";

$result = find_filters($input);
var_dump($result);

1 Comment

[a-z0-9_] with an i modifier is more simply written as \w.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.