0

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 :)

1 Answer 1

2

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.

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

5 Comments

Well, in this case it's only 3 values, but this is actually not always guaranteed to be the case...
what about stristr, would that be helpful?
@SoLoG strstr() isn't much different to using strpos() in this case.
Ok, Yeah, I suppose the foreach loop is needed here. Would a for loop be even faster? If I did a count on it first?
Don't worry about differences between for and while loops. That's micro-optimization and is an irrelevant distraction. Readability is far more important (and any differences are going to be insignificant anyway).

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.