Reputation: 49
I have some very long URL variables. Here is one example.
http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Ultimately it would be nice if I could find a way to use preg_replace
to simply change one variable even if in the middle of the string for instance in the string above change print=no
to 'print=yes
for example.
I will however settle for a preg_replace
pattern match that allows me to delete ?image=XYZ_1555025022.jpg
. as this is a variable the name could be anything. It will always have "?image"
" at the start and end with "&
"
I think one of the problems I have run into is that preg_match
seems to have issues on strings with "=" contained in them .
I am completely lost here in this and all those characters make may head spin. Maybe someone can give some guidance please?
Upvotes: 0
Views: 359
Reputation: 38552
You can use str_replace()
or preg_replace()
to get your job done, but parse_url()
with parse_str()
will give you more controls to modify any parameters easily by array index. Finally use http_build_query() to make your final url after modification.
<?php
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo "BEFORE".PHP_EOL;
print_r($query);
$query['print'] = 'yes';
echo "AFTER".PHP_EOL;
print_r($query);
?>
DEMO: https://3v4l.org/npGij
Upvotes: 1
Reputation: 147236
Here's a demo of how you can do some of things you want using explode
, parse_str
and http_build_query
:
$url = 'http://localhost/index.php?image=XYZ_1555025022.jpg&mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=no&mode=color&printscalewidth100=&printscaleheight100=&rand=56039';
// split on first ?
list($path, $query_string) = explode('?', $url, 2);
// parse the query string
parse_str($query_string, $params);
// delete image param
unset($params['image']);
// change the print param
$params['print'] = 'yes';
// rebuild the query
$query_string = http_build_query($params);
// reassemble the URL
$url = $path . '?' . $query_string;
echo $url;
Output:
http://localhost/index.php?mppdf=yes&pdfname=Printer&deskew=yes&autocrop=yes&print=yes&mode=color&printscalewidth100=&printscaleheight100=&rand=56039
Upvotes: 1