2

PHP has a function strpos() for finding the position of the first instance of a given value in a string. Is there a way to do this with a needle that is an array of strings? It would give the first occurence:

$str = '1st and 3rd';

str_array_pos($str, array('st', 'nd', 'rd', 'th')) //would return 1 because of 'st'
1
  • 1
    You could foreach over the needle array, do the strpos() and save the results in an array. You're looking for the min() of all the results. Commented Dec 2, 2010 at 0:04

2 Answers 2

3

You could write one yourself:

function str_array_pos($string, $array) {
  for ($i = 0, $n = count($array); $i < $n; $i++)
    if (($pos = strpos($string, $array[$i])) !== false)
      return $pos;
  return false;
}

By the way, the return value in your example should be 0 and not 1 since array indices start at 0.

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

2 Comments

This doesn't always return the position of the first occurence of any of the needle strings.
I agree with svens, this still won't be correct if another array element before the correct one also occurs in the string. For instance: str_array_pos('123', array('3', '2', '1')) returns 2 instead of 0, as it should.
1

array_search() will do that, test with ===false.

1 Comment

On second thought, I don't think this will work for your situation. @Casablanca - noticed right when you were commenting, yours is definitely the correct way, have a +1.

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.