PHP Regex - 如何附加到存在 <href> 的 URL(在包含大量文本的字符串变量中)


PHP Regex - How to append to a URL (in a string variable with a lot of text) where there is an <a href>

我正在研究构建Landingpages的自动化。

从单词文档复制/粘贴到TinyMCE文本区域,从而在输出中创建。

因此,如果我复制/粘贴这样的东西:

这是我的网站。

从 Word 文档 - 发送表单后的输出将如下所示:

This is my <a href="http://www.google.com">Website</a>.

我想附加到<a href>标签中的每个链接(仅在<a href>标签内!(如下:

?utm=foo_foo_foo

所以它看起来像这样:

This is my <a href="http://www.google.com?utm=foo_foo_foo">Website</a>.

PS:url 可以以"/"结尾或不以"/"结尾,这无关紧要,但应该双向工作。

P.S2:TinyMCR自己添加标签(如果你没有注意到我提到它..,(。我只需要附加到如下所示的字符串:

$string = "This is my <a href="http://www.google.com">Website</a>.";

你应该使用解析器,而不是正则表达式。

$html = 'This is my <a href="http://www.google.com">Website</a>.';
$dom = new DOMDocument(); 
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach($links as $link) {
    $link->setAttribute('href', $link->getAttribute('href') . '?utm=foo_foo_foo');
}
echo $dom->saveHTML();

输出:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p>This is my <a href="http://www.google.com?utm=foo_foo_foo">Website</a>.</p></body></html>

如果你必须使用正则表达式,你可以做

$html = 'This is my <a href="http://www.google.com">Website</a>.';
echo preg_replace('~href=("|'')(.+?)'1~', 'href=$1$2?utm=foo_foo_foo$1', $html);

输出:

This is my <a href="http://www.google.com?utm=foo_foo_foo">Website</a>.

这两种方法都假定您永远不会在URL中?