PHP正则表达式替换链接

时间:2011-11-28 16:07:56

标签: php regex preg-replace phpbb3

我有替换正则表达式(它取自phpbb源代码)。

$match = array(
                '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)" target\=\"_blank\">.*?</a><!\-\- \1 \-\->#',
                '#<!\-\- .*? \-\->#s',
                '#<.*?>#s',
            );
$replace = array( '\2',  '', '');

$message = preg_replace($match, $replace, $message);

如果我通过这样的消息运行它

asdfafdsfdfdsfds
<!-- m --><a class="postlink" href="http://website.com/link-is-looooooong.txt">http://website.com/link ... oooong.txt</a><!-- m -->
asdfafdsfdfdsfds4324

它返回此

asdfafdsfdfdsfds
http://website.com/link ... oooong.txt
asdfafdsfdfdsfds4324

但是我想把它变成一个替换功能。所以我可以通过提供href来替换块中的链接标题。

我想提供网址,新网址和新标题。所以我可以运行这些变量的正则表达式。

$url = 'http://website.com/link-is-looooooong.txt';
$new_title = 'hello';
$new_url = 'http://otherwebsite.com/';

它将返回相同的原始消息,但链接已更改。

<!-- m --><a class="postlink" href="http://otherwebsite.com/">hello</a><!-- m -->

我已经尝试过将它调整成这样的东西,但我无法做到这一点。我不知道如何建立匹配的结果,所以它在替换后具有相同的格式。

$message = preg_replace('#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="'.preg_quote($url).'" target\=\"_blank\">(.*?)</a><!\-\- \1 \-\->#', $replace, $message);

2 个答案:

答案 0 :(得分:1)

您会发现使用正则表达式解析HTML可能会非常困难并且变得非常复杂。最好的办法是使用DOM解析器like this one,然后用它来修改链接。

答案 1 :(得分:0)

您还需要在组中捕获其他部分,然后在替换中使用它们。尝试这样的事情:

$replace = '\1http://otherwebsite.com/\3hello\4';
$reg = '#(<!-- ([mw]) --><a (?:class="[\w-]+" )?href=")'.preg_quote($url).'("(?: target="_blank")?>).*?(</a><!-- \2 -->)#';
$message = preg_replace($reg, $replace, $message);

请参阅here

相关问题