Reputation: 2689
Ok, I'm feeling retarded here,
I have a string like so:
$string = 'function module_testing() {';
or it could be like this:
$string = 'function module_testing()';
or it could be like this:
$string = 'function module_testing($params) {';
or this:
$string = 'function module_testing($params, $another = array())';
and many more ways...
And than I have an array of strings like so:
$string_array = array('module_testing', 'another_function', 'and_another_function');
Now, is there some sort of preg_match
that I can do to test if any of the $string_array
values are found within the $string
string at any given position? So in this situation, there would be a match. Or is there a better way to do this?
I can't use in_array
since it's not an exact match, and I'd rather not do a foreach
loop on it if I can help it, since it's already in a while
loop.
Thanks :)
Upvotes: 0
Views: 92
Reputation: 625057
A foreach
loop here is the appropriate solution. Not only is it the most readable but you're looping over three values. The fact that happens within a while
loop is a non-issue.
foreach ($string_array as $v) {
if (strpos($string, $v) !== false) {
// found
}
}
You can alternatively use a regular expression:
$search = '\Q' . implode('\E|\Q', $string_array) . '\E';
if (preg_match('!$search!`, $string)) {
// found
}
There are two parts to this. Firstly, there is the |
syntax:
a|b|c
which means find a
, b
or c
. The second part is:
\Q...\E
which escapes the contents. This means if your search strings contain any regex special characters (eg (
) then the regex will still work correctly.
Ultimately though I can't see this being faster than the foreach
loop.
Upvotes: 2