我在一些使用旧系统的页面上有链接,例如:
<a href='/app/?query=stuff_is_here'>This is a link</a>它们需要转换为新系统,如下所示:
<a href='/newapp/?q=stuff+is+here'>This is a link</a>我可以使用preg_replace t0更改一些我需要的内容,但我还需要用+替换查询中的下划线。我当前的代码是:
//$content is the page html
$content = preg_replace('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#','$1="http://www.site.com/newapp/?q=$2"',$content);我想要做的是在$2变量上运行str_replace,所以我尝试使用preg_replace_callback,但始终无法使其工作。我该怎么办?
发布于 2011-09-01 18:41:57
使用dom解析文档,搜索所有的"a“标记,然后替换可能是一种很好的方法。已经有人在你的this link上发表了评论,告诉你正则表达式并不总是处理html的最佳方式。
这段代码总是可以工作的:
<?php
$dom = new DOMDocument;
//html string contains your html
$dom->loadHTML($html);
?><ul><?
foreach( $dom->getElementsByTagName('a') as $node ) {
//look for href attribute
if( $node->hasAttribute( 'href' ) ) {
$href = $node->getAttribute( 'href' );
// change hrefs value
$node->setAttribute( "href", preg_replace( "/\/app\/\?query=(.*)/", "/newapp/?q=\1", $href ) );
}
}
//save new html
$newHTML = $dom->saveHTML();
?>请注意,我使用preg_replace完成了此操作,但也可以使用str_ireplace或str_replace完成此操作
$newHref = str_ireplace("/app/?query=", "/newapp/?q=", $href);发布于 2011-09-01 18:33:55
或者,您可以简单地使用preg_match()并收集匹配的字符串。然后对其中一个匹配项应用str_replace(),并将"+“替换为"_”。
$content = preg_match('#href="\/[^\/]\/\?query=([^:"]+)#', $matches)
$matches[2] = 'newapp';
$matches[4] = str_replace('_', '+', $matches[4]);
$result = implode('', $matches)发布于 2011-09-01 18:52:34
将数组作为模式和替换传递给preg_replace:
preg_replace(array('|/app/|', '_'), array('/newappp/', '+'), $content);https://stackoverflow.com/questions/7268955
复制相似问题