preg_replace, str_replace and substr_replace not working in special condition

泪湿孤枕 提交于 2020-01-11 11:38:06

问题


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



来源:https://stackoverflow.com/questions/18630095/preg-replace-str-replace-and-substr-replace-not-working-in-special-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!