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