PHP 正则表达式 - 如何附加到 URL(在包含大量文本的字符串变量中),其中有 <a href>

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

我正在研究构建登陆页面的自动化。

A copy/pastes 从 word 文档到 TinyMCE textarea,它在输出中创建了。

所以如果我 copy/paste 是这样的:

This is my Website.

来自 word 文档 - 发送表单后的输出如下所示:

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

我想附加到 <a href> 标签内的每个 link( 仅在 <a href> 标签内!),如下所示:

?utm=foo_foo_foo

所以它看起来像这样:

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

P.S:网址可以以“/”结尾或不以“/”结尾,这无关紧要,但两者都应该有效。

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=("|\')(.+?)~', 'href=?utm=foo_foo_foo', $html);

输出:

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

这两种方法都假定您在 URL 中从未有过 ?..