preg_replace, str_replace and substr_replace not w

2019-03-02 02:12发布

问题:

I have the following code: this code finds all html tags in a string and replaces them with [[0]], [[1]] ,[[2]] and so on.(at least that is intented but not workinng);

$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);

This code finds all the tags in a string and replaces them with [[0]], [[1]] and [[2]] and so on. I have used preg_match_all with PREG_OFFSET_CAPTURE. The output of preg_match_all is as expected. However, preg_replace, substr_replace, and str_replace do not work when substituting the tags with [[$count]]. I have tried all three string replacement methods and none of them work. Please point me in the right direction. Can something in php.ini cause this? Thanks in advance.

回答1:

preg_replace does not substitute $str. Assign it to the string again:

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

Also, I'm not sure what you want exactly, but this I changed some things in the code, which seems to be what you were tying to do. I changed the regex a bit, especially the (.*?) part to ([^<>]+).



回答2:

the problem may be in this line

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

change it to this

foreach($out as $result) {

because i think you are accessing an index that doesn't exists