我有这个替换正则表达式(它取自 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);