解析字符串并将参数附加到PHP中的所有URL

时间:2012-07-23 09:27:29

标签: php parsing url

我有一个字符串,其中包含HTML中的网址。我想为每个网址添加参数。

$my_string = "See our full range of <a href="http://www.mysite.com/cat.php?cPath=8" target="_blank">some category</a> online and also our popular <a href="http://www.mysite.com/product.php?products_id=22" target="_blank">some product</a>.";

最终应该是:

$my_new_string = "See our full range of <a href="http://www.mysite.com/cat.php?cPath=8&new_param=test" target="_blank">some category</a> online and also our popular <a href="http://www.mysite.com/product.php?products_id=22&new_param=test" target="_blank">some product</a>.";

1 个答案:

答案 0 :(得分:0)

试试正则表达式:

$my_new_string = preg_replace('`<a (.*)href="(.+)"(.*)>`iU', '<a $1href="$2&new_param=test"$3>', $my_string);