PHP:如何使用stripos查找(用户定义的)字符串出现位置

PHP:如何使用stripos查找(用户定义的)字符串出现位置

问题描述:

There is strpos() to find First occurrence, and strrpos() to find last occurrence.

This tutorial explained that it's possible to get any occurrence using a loop, but that might be not fast when the haystack is big. And my code is looking ugly now.

Is there a way to find 2nd, 3rd, 4th, etc occurrence without looping over the haystack? I mean, finding the required occurrence directly without looping? Possible?

找到第一次出现的strpos()和找到最后一次出现的strrpos()。 p> \ n

这个教程解释说可以获得任何 使用循环发生,但当大海捞针很大时,这可能不会很快。 而且我的代码现在看起来很难看。 p>

有没有办法找到第二,第三,第四等发生而不会在大海捞针上循环? 我的意思是,直接找到所需的事件而不循环? 可能? p> div>

You can use a regular expression, but it will not be faster than looping with strpos.

if (preg_match_all("/(match this string)/g",$string,$matches))
{
   echo $matches[0] ; // this is the whole string
   echo $matches[1] ; // first match
   echo $matches[2] ; // second match
   echo $matches[3] ; // and so on
}

If you wan to replace those occurrences, use str_replace(). That way you don't have to worry about offsets.

You can use preg_match() with the PREG_OFFSET_CAPTURE flag so it'll capture all the matches as well as their position in the source string.

preg_match('/your string/', $source, $matches, PREG_OFFSET_CAPTURE);

$matches will be an array containing the offsets and copies of the matched string