1

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

2 回答 2

1

您会发现使用正则表达式解析 HTML 会很痛苦并且变得非常复杂。你最好的办法是使用一个 DOM 解析器,比如这个,然后用它来修改链接。

于 2011-11-28T16:09:48.387 回答
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);

这里

于 2011-11-28T16:41:01.880 回答