Link to home
Start Free TrialLog in
Avatar of EMB01
EMB01Flag for United States of America

asked on

Make Regex Get Inside HREF Tag

I have a regex (attached) that replaces href="http://www.emarketbuilders.com" and href="http://www.emarketbuilders.com/" with href="http://www.emarketbuilders.com/?uid=1&cid=1," for example.

I want the regex to also accept anything before the final quote in the href tag (a href="") and append the $uid and $cid variables.

Therefore, the regex should take these URLs:
http://www.emarketbuilders.com
http://www.emarketbuilders.com/
http://www.emarketbuilders.com/splash_page.php

And, append them, respectively:
http://www.emarketbuilders.com/?uid=1&cid=1
http://www.emarketbuilders.com/?uid=1&cid=1
http://www.emarketbuilders.com/splash_page.php?uid=1&cid=1

This change must only take place inside of link tags, such as a href.
<?php
 
$uid = 1;
 
$cid = 1;
 
$url = "<p>Therefore, the regex should take these URLs: <a href="http://www.emarketbuilders.com">URL 1</a> <a href="http://www.emarketbuilders.com/">URL 2</a><a href="http://www.emarketbuilders.com/splash_page.php">URL 3</a></p>
 
$result = preg_replace('|href="http://www.emarketbuilders.com/?"|', 'href="http://www.emarketbuilders.com/?uid='.$uid.'&cid='.$cid.'"', $url);
 
// And turn them into:
// http://www.emarketbuilders.com
// http://www.emarketbuilders.com/
// http://www.emarketbuilders.com/splash_page.php
 
echo $result;
 
?>

Open in new window

Avatar of phpmonkey
phpmonkey

try this:
$result = preg_replace('/(?:href=")[^"]*(?=")/i', '$0?uid=1&cid=1', $url);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of phpmonkey
phpmonkey

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shobinsun
Hello,

Use this:

$result = preg_replace('|www.emarketbuilders.com[a-zA-Z0-9._%&$#@?\/]*|', $myurl, $url);

Regards
Avatar of EMB01

ASKER

Thanks!
Avatar of EMB01

ASKER

Sorry, I didn't get a change to try the second solution. Though, it may have worked. The first seemed to work well enough (although, I also failed to try it in multiple scenarios, I only tried one $url).

Thanks for your help.