Page 1 of 1

how to replace links with other links with same title

Posted: Tue Aug 09, 2005 5:37 am
by jignesh
hello guys, i have a problem in replacing links with my own links. my situation is like this:

if paragraph contains any link then i wan to replace that link with my own link, but i want to append original link at the end of replaced link as a querystring paramater , for ex.

<a href='http://dell.com/?id=1'>dell</a> provides laptops.

i want to replace this link with

<a href='www.myurl.com/?u=http://dell.com/?id=1'>dell</a> provides laptops.

also i want to replace this link only if link contains sring like dell.com, i have written following regex for this, but it contains few bugs, but i dont understand.

Code: Select all

$src = "<a href='http://dell.com/?id=1'>dell</a> provides laptops.";
$url = "http://www.myurl.com/";
$highlight = "dell.com";
$search = "/<a href=(['\"])(.*?)$highlight(.*?)['\"](.*?)>(.*?)<\/a>/i";

$str = preg_replace($search, "<a href=$1$url$2$highlight$3$1>$5</a>", $src);
 
echo $str;
this code works fine for single link, but if i put source string like this:

Code: Select all

$src = "<a href='http://www.dell.com'  >dell</a> launched new laptops <a href='http://www.pcs.com/abc?id=1'>pcs</a> is also providing...";
and if i use above code for both domains , dell.com and pcs.com , it gives invalid output

please help me to solve this problem

Posted: Tue Aug 09, 2005 8:24 am
by feyd
viewtopic.php?t=36504

instead of using preg_match_all, like I posted in that thread, use preg_replace_callback()

it will possibly require some adjustment to match the entire link, but you should get the idea.