Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cut the string in string using PHP

There can be strings as follow,

p=aa&u=dd&p=ff
u=dd&p=ff
p=aa&u=dd
u=dd
p=aa&u=dd&p=ff&f=kk

I need to get u= value which is dd for now but u= value can be changed. It is always u= value.

I have trid following code for that,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

strstr("p=aa&u=dd&p=ff&f=kk","u=");

if (($tmp = strstr($str, 'u=')) !== false) {
    $str = substr($tmp, 2);
}

echo substr($str, 0, strpos($str, '&'));

This give dd value but when string is u=dd or p=aa&u=dd, not give any value. Which are u= part is end.

>Solution :

if you want to get what is after = you can try somehting like this :

Example #1 Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// Recommended
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
// DISCOURAGED
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
?>

Example #2 parse_str() name mangling

<?php
parse_str("My Value=Something");
echo $My_Value; // Something

parse_str("My Value=Something", $output);
echo $output['My_Value']; // Something
?>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading