Preg_replace或preg_replace_callback?

问题描述:

我会对使用旧系统,如一些网页链接:Preg_replace或preg_replace_callback?

<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,并且永远无法得到它的工作。我该怎么办?

+2

*(相关)* [解析HTML的最佳方法](http://*.c om/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon

你要通过有效的callback [docs]作为第二个参数:一个函数名,匿名函数等

下面是一个例子:

function my_replace_callback($match) { 
    $q = str_replace('_', '+', $match[2]); 
    return $match[1] . '="http://www.site.com/newapp/?q=' . $q; 
} 
$content = preg_replace_callback('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#', 'my_replace_callback', $content); 

或用PHP 5.3:

$content = preg_replace_callback('#(href)="http://www.site.com/app/?query=([^:"]*)(?:")#', function($match) { 
    $q = str_replace('_', '+', $match[2]); 
    return $match[1] . '="http://www.site.com/newapp/?q=' . $q; 
}, $content); 

您可能还想尝试使用HTML解析器而不是正则表达式:How do you parse and process HTML/XML in PHP?

+0

感谢这正是我一直在寻找的! – james

或者您可以简单地使用preg_match()并收集匹配的字符串。然后将str_replace()应用于其中一个匹配项,并将“+”替换为“_”。

$content = preg_match('#href="\/[^\/]\/\?query=([^:"]+)#', $matches) 
$matches[2] = 'newapp'; 
$matches[4] = str_replace('_', '+', $matches[4]); 
$result = implode('', $matches) 

用dom解析文档,搜索所有“a”标签,然后替换可能是一个好方法。有人已经发表评论张贴你this link告诉你,正则表达式并不总是使用html的最佳方式。

Ayways此代码应工作:

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

通行证阵列preg_replace的模式和替代:

preg_replace(array('|/app/|', '_'), array('/newappp/', '+'), $content);