Forum Moderators: coopster

Message Too Old, No Replies

Regex to re-write urls with a variable on the end

         

dan121

9:07 pm on Jul 28, 2005 (gmt 0)

10+ Year Member



I'm trying to rewrite urls on a page. What I want to do is add a variable to each one, so <a href="/link">Text</a> becomes <a href="/link?var>Text</a>

The variable would stay the same for every url on the page.

I'd like it to work only with local links, that start with a slash or not: href="link" or href="/link" but not to rewrite external links: href="http://example.com" Also, if there are already variables in the link, I'd just like to append to them, so that href="/link?var1=1&var2=2" becomes href="/link?var1=1&var2=2&var"

I assume I'd use preg_replace...but am lost as to the regex. Hope that all makes sense! Thanks for any help!

mattx17

9:20 pm on Jul 28, 2005 (gmt 0)

10+ Year Member



Hi dan121,

Try taking a look at the parse_url function (http://www.php.net/parse_url). Passing your href value to this function will return a nice array of data about the URL.

For instance:

parse_url("/links?var1=1&var2=2");

will yield

Array
(
[path] => /links
[query] => var1=1&var2=2
)

Hope that points you in the right direction!