preg_replace,str_replace和substr_replace在特殊条件下不工作


preg_replace, str_replace and substr_replace not working in special condition

我有以下代码:此代码查找字符串中的所有 HTML 标记,并将它们替换为 [[0]]、[[1]]、[[2]] 等。(至少这是有意的,但不是有效的);

$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);
$count = 0;

foreach($out[0] as $result) {
$temp=preg_quote($result[0],'/');
$temp ="/".$temp."/";
preg_replace($temp, "[[".$count."]]", $str,1);

$count++;   
}
var_dump($str);

此代码查找字符串中的所有标记,并将它们替换为 [[0]]、[[1]] 和 [[2]] 等。我用preg_match_all和PREG_OFFSET_CAPTURE。preg_match_all的输出符合预期。但是,preg_replacesubstr_replacestr_replace 在用 [[$count]] 替换标签时不起作用。我已经尝试了所有三种字符串替换方法,但没有一种有效。请指出我正确的方向。php.ini中的某些东西会导致这种情况吗?提前谢谢。

preg_replace 不替换$str 。再次将其分配给字符串:

$str = preg_replace($temp, "[[".$count."]]", $str);

另外,我不确定你到底想要什么,但我改变了代码中的一些东西,这似乎是你要做的。我稍微更改了正则表达式,尤其是(.*?)部分为 ([^<>]+).

问题可能出在这一行

foreach($out[0] as $result) {

将其更改为此

foreach($out as $result) {

因为我认为您正在访问一个不存在的索引