preg_match to strip link from content


I am using this bit of code to identify certain links within my content and swap them for another link.

$re1='(\\\\[url\\\\])';	# Square Braces 1
$re2='.*';	# Non-greedy match on filler
$articleContent .=preg_replace("/".$re1.$re2.$re3."/i", '<a href="">Sign Up For Access</a>', $resource[1]);

The problem with it is that it replaces everything between the tags what I want to do is replace ONLY the url and leave the rest intact.

What would the reg_ex look like to accomplish this?


the slashes make my head hurt.

So you want to take anything between


and make it into $resource[1]? Cause… your example there doesnt use the tags…

EDIT: lol. go go BBCode translator. Wrapped in PHP tags to prevent translation.

Bah. Got the parameters backwards in my head. Okay so you want to take anything between square bracketed URL tags and replace it with a fixed string…
What exactly did you want to ‘save’ from the original string? Display it where? Give me an example of your input, followed by what you want it to look like when you’re done.


Thanks for replying. It is just standard formatted text (as supplied by ckeditor)

An example of this could be…

<span style="font-size: 14px;"><span style="color: rgb(0, 102, 255);"><span style="font-family: verdana,geneva,sans-serif;"><strong>Heart to Heart: Building Connections With Hard-to-Reach Students</strong></span></span></span></p>
	<span style="color: rgb(178, 34, 34);"><strong><span style="font-size: 14px;"><span style="font-family: verdana,geneva,sans-serif;">Replay pack Available:</span></span></strong></span><a href="" target="_blank"><span style="font-size: 14px;"><span style="font-family: verdana,geneva,sans-serif;"><strong>Now</strong></span></span></a></p>

I need to grab the url from within a link that is surrounded by the url/url and replace that url with another. Now I need to identify the link by url/url because there are some links on the page that do not require them to be changed.

I hope that is enough to go on.

Thanks for helping

You would need to use a backreference, in order to retrieve values from the original string.

So if you have

<a href=''>Google</a>

You would write it as (note: i didn’t test this, just for illustration)

    $url = preg_replace("~\\[url\\]<a.*?>(.*?)</a>\\[\\/url\\]~", "<a href=''>\\\\1</a>", $string);

Also, “non-greedy” requires a ? after .*

Hi Wonshikee.

Thanks so much for that, It worked perfectly out of the bag!


side note: The \ infront of the / is unneeded because you’re using ~ as a delimiter, instead of /.