PHP “preg_replace” to add query param to any urls of a certain domain

£可爱£侵袭症+ 提交于 2019-12-11 13:32:13

问题


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!


回答1:


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 :)




回答2:


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>"));


来源:https://stackoverflow.com/questions/11368129/php-preg-replace-to-add-query-param-to-any-urls-of-a-certain-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!