PHP “preg_replace” to add query param to any urls

2019-07-31 17:14发布

I have a string like:

$description = '
<a href="http://www.replace.com/1st-link/">1st link in string</a>,
<a href="http://www.ignore.com/">2nd link in string</a>, some other text in string,
<a href="http://www.replace.com/3rd-link/">3rd link in string</a>.
';

I need to use preg_replace to append a query parameter of "?id=awesome" to any urls in the $description string from "replace.com" (ignoring all other links, i.e. "ignore.com").

Thanks in advance for any help!

2条回答
叼着烟拽天下
2楼-- · 2019-07-31 17:52

Ok, simple enough, here you go:

$content = preg_replace('/http:\/\/[^"]*?\.replace\.com\/[^"]+/','$0?id=awesome',$description);

Hope that's it, $content will have the string witht he added paramters to the replace.com domain :)

查看更多
姐就是有狂的资本
3楼-- · 2019-07-31 18:01

I would strongly advise using a DOM parser instead of a regex. For instance:

$description = '...';
$wrapper = "<root>".$description."</root>";
$dom = new DOMDocument();
$dom->loadXML($wrapper);
$links = $dom->getElementsByTagName('a');
$count = $links->length;
for( $i=0; $i<$count; $i++) {
    $link = $links->item($i);
    $href = $link->getAttribute("href");
    if( preg_match("(^".preg_quote("http://www.replace.com/").")i",$href))
        $link->setAttribute("href",$href."?id=awesome");
}
$out = $dom->saveXML();
$result = substr($out,strlen("<root>"),-strlen("</root>"));
查看更多
登录 后发表回答