开发者

Find position first occurence of an array of strings in a string

开发者 https://www.devze.com 2023-01-27 17:51 出处:网络
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 occu

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 r开发者_Go百科eturn 1 because of 'st'


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消