2011-09-01 73 views
3

我會對使用舊系統,如一些網頁鏈接: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://stackoverflow.c om/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon

回答

3

你要通過有效的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

0

或者您可以簡單地使用preg_match()並收集匹配的字符串。然後將str_replace()應用於其中一個匹配項,並將「+」替換爲「_」。

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

用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); 
0

通行證陣列preg_replace的模式和替代:

preg_replace(array('|/app/|', '_'), array('/newappp/', '+'), $content); 
相關問題