这可以通过 preg_match_all 和 PREG_OFFSET_CAPTURE FLAG 来完成。
例如
$str="some text <a href='/review/'>review</a> here <a class='abc' href='/about/'>link2</a> hahaha";
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",$str,$out,PREG_OFFSET_CAPTURE);
var_dump($out);
这里的输出数组是$out。PREG_OFFSET_CAPTURE捕获模式开始的字符串中的偏移量。
上面的代码将输出:
array (size=2)0 =>
array (size=2)
0 =>
array (size=2)
0 => string '<a href='/review/'>review</a>' (length=29)
1 => int 10
1 =>
array (size=2)
0 => string '<a class='abc' href='/about/'>link2</a>' (length=39)
1 => int 45
1 =>
array (size=2)
0 =>
array (size=2)
0 => string 'review' (length=6)
1 => int 29
1 =>
array (size=2)
0 => string 'link2' (length=5)
1 => int 75
有关更多信息,您可以单击链接http://php.net/manual/en/function.preg-match-all.php
for $changedStr: 让 $out 成为 preg_match_all 的输出字符串
$count= 0;
foreach($out[0] as $result) {
$temp=preg_quote($result[0],'/');
$temp ="/".$temp."/";
$str =preg_replace($temp, "[[".$count."]]", $str,1);
$count++;
}
var_dump($str);
这给出了输出:
string 'some text [[0]] here [[1]] hahaha' (length=33)