2011-07-05 59 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);