preg_replace用于修改URL

时间:2011-11-12 14:05:41

标签: php regex url preg-replace pattern-matching

我正在尝试更新数据库中的某些网址。

以下是我正在处理的主题文本的一部分:

abcd abc(<a href=http://www14.xx.com/banket00/xx.aspx?id=384>abc</a>). abc ab %30-40 abcd. <a href=http://www.xx.edu.it/~xx/xxx.html target=_blank>abc</a> abcd xxx.

(7061, 931, 'xx', 'xx. <a class=''abc'' href=xx.aspx?id=1657 target=right>"xxxx! xxx</a>', 1, NULL, 0, '2005-02-07 17:47:00', 0),

xx <a class=''abc'' href=xx.aspx?id=4340 target=right>xxx</a>''xxx.<br>04 x  2007  : xxxx.com 33000 xxxxxx.', 1, '2007-11-04 18:13:00', 0, '2007-11-04 16:12:00', 0),

(35761, 5257, 'xxxx', '<a href="http://x.org.global-x.com/xxx.aspx?id=5249&jj=1" target=_blank>http://x.org.global-x.com/xxxx.aspx?id=5249&jj=1</a>', 1, '0000-00-00 00:00:00', 0, '2009-03-21 12:08:00', 0),

我要做的是将包含“aspx?id = x”的网址更新为

'<a href="#" onclick="func(<id_in_url>)"><text_of_link></a>'

到目前为止,我已经尝试了很多模式,其中一些模式适用于某些URL,但我提出的最新模式不起作用:

pattern: /<a[ class='*abc'*]* href=[a-zA-Z\.-_\/:'"]*?\?id=(\d+)"*[ target=[right|_blank]]*>([^<]*?)<\/a>/i

replacement: '<a href="#" onclick="func($1)">$2</a>'

3 个答案:

答案 0 :(得分:0)

您的链接是否必须符合条件?如果不是,我认为它有效:

<a[^>]*aspx\?id=(\d+)[^>]*>([^<]+)</a>

答案 1 :(得分:0)

<?php
$string = 'abcd abc(<a href=http://www14.xx.com/banket00/xx.aspx?id=384>abc</a>). abc ab %3';
$pattern = '/<a[^>]+aspx\?id=([0-9]*)[^>]*>([^<]*)<\/a>/i';
$replacement = '<a href="#" onclick="func($1)">$2</a>';

echo preg_replace($pattern, $replacement, $string);

答案 2 :(得分:0)

使用:

/<a (?:.*?)\bhref=(?:.*?)\?id=(\d+)\b(?:.*?)>([^<]*?)<\/a>/is
相关问题