2011-07-05 61 views
1

原話需要幫助的PHP替代詞

$string = '<a href="/home/top">here is some text</a>. <a href="/links/abc">some links here</a>...'; 
//more links and other html. more link like <a href="/home/below">, <a href="/links/def">... 

我需要改變

<a href="/links/abc"> => <a href="#" onclick="link('abc|123')"> 
<a href="/links/def"> => <a href="#" onclick="link('def|123')"> 
<a href="/links/ghi"> => <a href="#" onclick="link('ghi|123')"> 

我試圖用str_replace,但它只是簡單的更換<a href="<a href="#" onclick="link(',難以判斷下一部分。但如何處理這些替換?謝謝。

+1

可以使用的preg_replace使用正則表達式。這個主題有很多教程。 http://php.net/manual/en/function.preg-replace.php和http://www.phpf1.com/tutorial/php-regular-expression.html – Fender

+0

@Fender,你可以爲我寫嗎?謝謝。 –

回答

1

可以使用的preg_replace():

$string = preg_replace('%href="/links/(.+?)"%', 'href="#" onclick="link(\'$1|123\')"', $string); 
2

模式:$pattern = '@<a href=\"/links/([a-zA-Z0-9]*)\">@is';

取代:$replace = '<a href="#" onclick="link(\'\1|123\')">';

電話:$result = preg_replace($pattern, $replace, $string);