PHP manipulate string (find/replace if value exists) - php

I have a text string that is set in a variable to a value like these:
$str = 'type=showall'
or
$str = 'type=showall&skip=20'
$str = 'type=showall&skip=40'
$str = 'type=showall&skip=60'
and so on.
I need to check to see if there is a "skip" value present in the string, and if so replace it with a new number that is stored in a $newSkip variable and keep the string the same except for the change to the skip value.
For example if the string was:
$str = 'type=showall&skip=20'
and
$newSkip = 40
then I would like this to be returned:
$str = 'type=showall&skip=40'
If there was no skip value:
$str = 'type=showall'
and
$newSkip = 20
then I would like this to be returned:
$str = 'type=showall&skip=20'
I'm fairly new to PHP so still finding my way with the various functions and not sure which one/s are the best ones to use in this scenario when the text/value you're looking for may/may not be in the string.

PHP has a handy function called parse_str() which accepts a string similar to the one you have, and returns an array with key/value pairs. You'll then be able to inspect specific values and make the changes you need.
$str = 'type=showall&skip=20';
// this will parse the string and place the key/value pairs into $arr
parse_str($str,$arr);
// check if specific key exists
if (isset($arr['skip'])){
//if you need to know if it was there you can do stuff here
}
//set the newSkip value regardless
$arr['skip'] = $newSkip;
echo http_build_query($arr);
The http_build_query function will return the array into the same URI format that you started with. This function also encodes the final string so if you want to see the decoded version, you'll have to send it through urldecode().
References -
parse_str()
http_build_query()

Related

How to check preg_match for complicated text?

I've already seen some posts about it, but my text is a bit complicated,
And I can not get it to work.
Part of my page:
otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}}
What I tried:
preg_match("/otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=(.*)/", $data[$n], $output);
echo $output[1];
What I want to present:
Just the number after uid=*
If the string you receive is reliably formatted like your posted examples, where the uid= parameter is the first query parameter after ? and is strictly a numeric string, you can use preg_match() to extract it by matching with (\d+) (match digits) because whatever follows in the next query parameter won't begin with a digit.
$str = 'otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}}';
preg_match('/\?uid=(\d+)/', $str, $output);
echo $output[1];
// Prints "35577"
In practice I would avoid this though. The best way to handle this is to treat it as the JSON stream it is, in combination with PHP's built-in URL handling methods parse_url() and parse_str().
That solution looks like:
// Note: I made this segment a valid JSON string...
$input_json = '{"otherurl":"http:\/\/cdn1-test.peer5.net:80\/edge\/71-1.stream\/playlist.m3u8?uid=35577\u0026sil=3\u0026sip=WyIxODUuMTgueC54IiwiMjEwLj4LngiLCI54LngLjE1OC5giXQ%3D%3D\u0026sid=151078248\u0026misc=4OFxyLUs7UrIeWujPzuU%3D"}';
$decoded = json_decode($input_json, TRUE);
// Parse the URL and extract its query string
// PHP_URL_QUERY instructs it to get only the query string
// but if you ever need other segments that can be removed
$query = parse_url($decoded['otherurl'], PHP_URL_QUERY);
// Parse out the query string into array $parsed_params
$params = parse_str($query, $parsed_params);
// Get your uid.
echo $parsed_params['uid'];
// Prints 35577

How to change integer value in preg_match PHP?

sorry if my question was stupid, please someone help me to fix this issue.
i have string like
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
this $str_value is dynamic , it will change each page. now i need to replace 9 in this string as 10. add integer 1 and replace
for example if the $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/251/"
then output should be
http://99.99.99.99/var/test/src/158-of-box.html/252/
i tried to replace using preg_match but i m getting wrong please somesone help me
$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );
Thank's for the answer, #Calimero! You've been faster than me, but I would like to post my answer, too ;-)
Another possibilty is to fetch the integer by using a group. So you don't need to trim $matches[0] to remove the slashes.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
return '/'.($matches[1]+1).'/';
}, $str_value);
echo $str;
You need to use a callback to increment the value, it cannot be done directly in the regular expression itself, like so :
$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("#/\\d+/#",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/
Basically, the regexp will capture a pure integer number enclosed by slashes, pass it along to the callback function which will purge the integer value, increment it, then return it for replacement with padded slashes on each side.
I'd suggest also another approach based on explode and implode instead of doing any regexp stuff. In my opinion this is more readable.
$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";
// explode the initial value by '/'
$explodedArray = explode('/', $str_value);
// get the position of the page number
$targetIndex = count($explodedArray) - 2;
// increment the value
$explodedArray[$targetIndex]++;
// implode back the original string
$new_str_value = implode('/', $explodedArray);

Parse a string in php

I am wondering how I can parse this string to get a certain name or string. What I need to parse is:
items/category/test.txt
To get it with out test.txt of course there will be different names so I can't just replace it.
I need the result to be:
items/category/
Also how can I parse it to get /category/ only?
Use PHP's pathinfo() function:
http://php.net/manual/en/function.pathinfo.php
$info = pathinfo('items/category/test.txt');
$dirPath = $info['dirname'];
// OR
$dirPath = pathinfo('items/category/test.txt', PATHINFO_DIRNAME);
// Output: items/category
Use explode to get the above string as array
$string = "tems/category/test.txt";
$string_array = explode("/",$string);
print_r($string_array); // Will Output above as an array
// to get items/category/
$var = $string_array[0].'/'.$string_array[1];
echo $var; //will output as items/category/
$var2 = '/'.$string_array[1].'/';
echo $var2; //will output as /category/
I believe your best chance is explode("/","items/category/test.txt") .
This will splice the string every time it finds / returning an array, whereas implode (join is an alias of it) will join an array of strings, so
$spli=explode("/","items/category/test.txt");
implode($spli[0],$spli[1]);
Should do the trick for the first case, returning items/category
For category alone, $spli[1] is enough.
Of course, you may pass the string as a variable, for instance
$foo="items/category/test.txt;"
explode("/",$foo);
etc.

is string an array in php

you can do numeric index in string like in array.
ex.
$text = "esenihc gnikcuf yloh";
echo $text[0];
echo $text[1];
echo $text[2];
...................
...................
...................
But if you put string in print_r() not same will happen like in array and you cant do count() with string.
I read the documentation and it says.
count()
return 1 if not an array in the parameter
print_r()
if string is in parameter it just prints that string.
this is not the exact word but something like this.
Why both these functions dont treat string same as an array?
So final question is string an array?
Unlike for example C, PHP has an inbuilt string datatype. The string datatype allows you array-like access to the single characters in the string but will always be a string. So if you pass it to a function that accepts the mixeddatatype this function will determine the datatype of the passed argument and treat it that way. That is way print_r() will print it in the way it was programmed to output strings and not like an array.
If you want a function that works does the same as count for arrays have a look at strlen.
If you want you can "turn" your string into an array through str_split.
A string is an array if you treat it as an array, eg: echo $text[0], but print_r Prints human-readable information about a variable, so it will output that variable.
It's called Type Juggling
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a; // bar
To count a string's length use strlen($string) then you can for a for()
no a string is no array
A string is series of characters, where a character is the same as a byte and An array in PHP is actually an ordered map. A map is a type that associates values to keys.
simply everything in the sense every variable in PHP is an array.
Maybe too late but:
<?php
$text = "esenihc gnikcuf yloh";
$arrText = explode(" ", $text);
foreach($arrText as $word) {
echo $word . "<br>";
}
?>

Parse variables within string

I'm storing some strings within a *.properties file. An example of a string is:
sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.
My function takes the value from sendingFrom and then outputs that string on the page, however it doesn't automatically parse the {$oEmails->agentName} within. Is there a way, without manually parsing that, for me to get PHP to convert the variable from a string, into what it should be?
If you can modify your *.properties, here is a simple solution:
# in file.properties
sendingFrom = Sending emails from %s, to %s people.
And then replacing %s with the correct values, using sprintf:
// Get the sendingFrom value from file.properties to $sending_from, and:
$full_string = sprintf($sending_from, $oEmails->agentName, $oEmails->customerCount);
It allows you to separate the logic of your app (the variables, and how you get them) from your presentation (the actual string scheme, stored in file.properties).
Just an alternative.
$oEmails = new Emails('Me',4);
$str = 'sendingFrom=Sending emails from {$oEmails->agentName}, to {$oEmails->customerCount} people.';
// --------------
$arr = preg_split('~(\{.+?\})~',$str,-1,PREG_SPLIT_DELIM_CAPTURE);
for ($i = 1; $i < count($arr); $i+=2) {
$arr[$i] = eval('return '.substr($arr[$i],1,-1).';');
}
$str = implode('',$arr);
echo $str;
// sendingFrom=Sending emails from Me, to 4 people.
as others mentioned eval wouldn't be appropriate, I suggest a preg_replace or a preg_replace_callback if you need more flexibility.
preg_replace_callback('/\$(.+)/', function($m) {
// initialise the data variable from your object
return $data[$m[1]];
}, $subject);
Check this link out as well, it suggests the use of strstr How replace variable in string with value in php?
You can use Eval with all the usual security caviats
Something like.
$string = getStringFromFile('sendingFrom');
$FilledIn = eval($string);

Categories