PHP正则表达式来替换链接


PHP regular expression to replace links

我有这个替换正则表达式(它取自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,新url和新标题。我可以用这些变量运行一个正则表达式。

$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);

您会发现使用regex解析HTML可能是一件痛苦的事情,而且会变得非常复杂。最好的方法是使用像这样的DOM解析器,并用它来修改链接。

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

$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);