php中替换特定块的实现
今天在csdn上面有人提出了替换特定块的需求,看了一下,觉得挺有意思,于是一路跟进,最后有一些答案,给记录下来。
提问如下:
<a href="">中华人民共和国中华人民共和国\n</a>\n\n
或者
<a href="">\n中华人中华人民共和国\n</a>
这样的字符串中a标签的\n我怎么用正则替换掉啊????
$line = '<a href="">\n中华人民共和国中华人民共和国\n</a>\n\n保留!<a href="">baidu\n你好</a>保留\n保留<a href="">谷歌\n走了</a>保留\n保留';
# preg_match_all ("#<a[^>]*>([^<]+)</a>#", $line, $matches);
# var_dump($matches);
echo preg_replace_callback(
"#<a[^>]*>([^<]+)</a>#",
create_function(
// single quotes are essential here,
// or alternative escape all $ as \$
'$matches',
'return str_replace(\'\\n\', "", $matches[0]);'
),
$line
);
$rawText = preg_replace("/(<a.*?>.*?<\/a>)/sie", "str_replace('\\n',\"\",stripslashes(\"\$1\"))", $rawText);
$str = '<a href="">\n中华人民共和国中华人民共和国\n</a>\n\n保留!<a href="">baidu\n你好</a>保留\n保留<a href="">谷歌\n走了</a>保留\n保留';
$patten = '#<a.+?href="(.*?)".*?>(.+?)</a>#';
$result=array();
$tmp=array();
preg_match_all($patten,$str,$arr);
for($i=0;$i<count($arr[2]);$i++){
$tmp[$i] = str_replace('\n','',$arr[2][$i]);//清除换行
$result[$i] = str_replace($arr[2][$i],$tmp[$i],$str);
$str = $result[$i];//替换的内容重新赋值
}
echo str_replace('\n',"\n",$result[count($arr[2])-1]);