Forum Moderators: coopster
I'm using the following to try and replace urls in my html output:
$newhrefs = preg_replace("/script.php\?(.*)=(.*)&(.*)=(.*)&(.*)=(.*)/",
"script-$1-$2-$3-$4-$5-$6.html", $hrefs);
This works fine as long as there are exactly 3 var=val pairs... not 1 or 2 or 4 or more...
How can I write my expression to match 1 or more pairs? For example:
script.php?var=val
script.php?var=val&var2=val2
script.php?var=val&var2=val2&var3=val3
script.php?var=val&var2=val2&var3=val3&var4=val4
etc...etc...etc...
TIA,
Shawn
Here is what I have now, but I was hoping to combine the regexes and replacements from the array elements into to 1 regex.
$search = array(
"/(script).php\?((\w+)=(\w+))/",
"/&((\w+)=(\w+))*$/",
"/&((\w+)=(\w+))*/",
);
$replace = array(
"$1-$3-$4",
"-$2-$3.html",
"-$2-$3",
);
$newhrefs = preg_replace($search, $replace, $hrefs);
Thanks!
Shawn
$test = '<a href="script.php?name=aaron&age=15">Aaron</a>';
#
echo preg_replace("'script.php\?([^\"]+)'e",
"'script-'.implode('-', preg_split('/&¦=/', '\\1')).'.html'",
$test);
will echo() [php.net]
script-name-aaron-age-15.html. BOL´s idea pointed into the right direction. Doing the matching for any given number of parameter using a single regular expression would be quite hard. That is why I choose to extract the entire query string using preg_replace() [php.net], "storing" it in the backreference \1 and then split it up using preg_split() [php.net]. The array returned is then implode() [php.net]d. Then 'script-' and '.html' get concatenated to the resulting string.
The replacement string is evaluated because of the e pattern modifier.
HTH Andreas
Well you sure do need to use a regex but you do not need to do it all in one RewriteRule [httpd.apache.org] at once.
RewriteRule [httpd.apache.org] (script.*)-([^-]+)-([^-]+)\.html$ $1?$2=$3 [N,QSA]
RewriteRule [httpd.apache.org] script\.html script.php
will loop over the URL until all -parameter-value pairs are removed from the URI and added to the query string. Then script.html will be rewritten to script.php.
Andreas