Forum Moderators: coopster

Message Too Old, No Replies

Regex problems...

Getting my head around regular expressions

         

mnet1

9:38 pm on Mar 15, 2003 (gmt 0)

10+ Year Member



I have been reading up on regex etc but despite what I try I can't seem to get my PHP preg_replace's to work the way I want.

Basically all I'm looking to do is replace all linked URLs in a string with links to a PHP file as follows


<a href="hello.html?db=blahblah">Hi</a><a target="_blank" href="goodbye.html">goodbye.html</a>

... becomes ...


<a href="index.php?file=hello.html&db=blahblah">Hi</a><a target="_blank" href="index.php?file=goodbye.html">goodbye.html</a>

You'll note two unique things about this - a) I need it to be able to handle pre-existing query strings as per the hello.html example and b) I only want linked URLs to be replace, not every URL (as per goodbye.html).

Any thoughts / code would be very much appreciated - I've been beating my head against this wall for a few days now :(

DrDoc

9:45 pm on Mar 15, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to Webmaster World!

How about this:

$newstring = preg_replace("/href=\"/","href=\"index.php?file=",preg_replace("/\?/","&amp;",$oldstring));

edited typos

DrDoc

9:54 pm on Mar 15, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Maybe I should explain what the code does, too:

preg_replace("/\?/","&amp;",$oldstring)
replaces any?'s with "&" (I'm using the HTML entity &amp; here).

The other preg_replace replaces href=" with href="index.php?file=

Hence,

href="hello.html?db=blahblah"
would be
href="hello.html[b]&[/b]db=blahblah"
after the first preg_replace, and then
href="[b]index.php?file=[/b]hello.html&db=blahblah"
after the second.

href="goodbye.html"
remains unchanged in the first preg_replace, but becomes
href="[b]index.php?file=[/b]goodbye.html"
after the second.

mnet1

10:27 pm on Mar 15, 2003 (gmt 0)

10+ Year Member



Thanks so much for that! Other than a missing ')' it worked straight out of the box :)

Thanks also for the welcome, this seems like a great community.