preg_replace a part of a string with variable - php

I have a string that looks a little something like this:
$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';
And I would like to make another string from that, and replace it with a value, so for example it will look like this
$newstring = 'var1=foo&var2=bar&var3=$myVariable&etc=etc';
so var3 in the new string will be the value of $myVariable.
How can this be achieved?

No need for regex; built in URL functions should work more reliably.
// Parse the url first
$url = parse_url($string);
// Parse your query string into an array
parse_str($url['query'], $qs);
// Replace the var3 key with your variable
$qs['var3'] = $myVariable;
// Convert the array back into a query string
$url['query'] = http_build_query($qs);
// Convert the $url array back into a URL
$newstring = http_build_url($url);
Check out http_build_query and parse_str. This will append a var3 variable even if there isn't one, it will URL encode $myVariable, and its more readable than using preg_replace.

You can use the method preg_replace for that. Here comes an example
<?php
$string = 'var1=foo&var2=bar&var3=blahblahblah&etc=etc';
$var = 'foo';
echo preg_replace('/var3=(.*)&/', 'var3=' . $var . '&', $string);

Related

Extract String From String in PHP

I have string variable like ABC/DF/G I want extract DF from it means text between two /.
I have tried like below
$string= "ABC/DF/G";
$code = substr($string ,strpos($string,'/'));
echo $code;
but I am getting result like below
/DF/G
Let me know if someone can help me for do it.
Thanks!
You can use explode function to split a string into an array.
$string= "ABC/DF/G";
$code = explode('/', $string);
echo $code[1];

Using preg_replace on url variables

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?
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
Demo on 3v4l.org
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

How to append a string in between a url in PHP

I want to add a string between a url string using PHP.
$link = 'http://localhost/wordpress/mypage';
$string = 'nl/';
I want the new link to be like this:
$newlink = 'http://localhost/wordpress/nl/mypage';
Here is one-of-the way to achieve it, using substr_replace():
$someString = 'http://localhost/wordpress/mypage';
$string = 'nl/';
echo substr_replace($someString, $string, strpos($someString, 'mypage'), 0);
Output:
http://localhost/wordpress/nl/mypage
Another method using str_replace():
$someString = 'http://localhost/wordpress/mypage';
echo str_replace('wordpress/', 'wordpress/nl/', $someString);
this is an easiest way you can do.
$string = 'nl/';
$link = 'http://localhost/wordpress/'.$string.'mypage';
You can set the $string dynamic or static as you wanted to.
echo $link; Result : http://localhost/wordpress/nl/mypage

PHP regex: How to extract url and filter "\" from specific string

I'm a newbie with programming; now, I have some problems with PHP programing.
I want to extract the URL from the following stringļ¼š
"success":true,"load":"http:\/\/8.88.88.8\/list\/si3diwoe\/123","Live":true
The desired string is
http://8.88.88.8/list/si3diwoe/123
Can anyone tell me how this work in code?
Thank you very much!
$string = '"success":true,"load":"http:\/\/8.88.88.8\/list\/si3diwoe\/123","Live":true';
// The JSON way
$array = json_decode('{' . $string . '}'); // Wrap in {} to make object
$url = $array->load;
echo "Using JSON : $url", PHP_EOL;
// The RegEx way
preg_match('/load":"(.*?)"/', $string, $matches);
$url = stripslashes($matches[1]);
echo "Using RegEx: $url", PHP_EOL;
Output:
Using JSON : http://8.88.88.8/list/si3diwoe/123
Using RegEx: http://8.88.88.8/list/si3diwoe/123
If it's a json string, you can use json_decode to assign it to a variable, say $arr, then stripslashes($arr['load']);
if it's not, you can use explode("," , $string), and assign it to a variable, say $arr again. Run explode again (explode(":", $arr[1])) and assigned it to another variable, say $ar, then do stripslashes on $ar['1'];

String at the end of a text inside another string

I would like to use one string inside another string, like this:
$url = "http://www.sample.com/index.php?nr=$string[0]";
how should I insert this string at the end?
$url = "http://www.sample.com/index.php?nr={$string[0]}";
or
$url = "http://www.sample.com/index.php?nr=" . $string[0];
just like your example
$url = "http://www.sample.com/index.php?nr=$string[0]";
As a solution to your problem please try executing following code snippet.
You need to concatenate strings in php using dot operator(.)
$url = "http://www.sample.com/index.php?nr=".$string[0];

Categories