I have a query string such as this:
file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3
I need to extract all the genres mentioned in the string, in this case its
genre1, genre4, genre19 and genre18
and output them into a string such as
ge1_ge4_ge19_ge18
What would be a good solution for this?
If you want the parameters passed by query string to the currently executing script then you simply need:
$genres = preg_grep('!^genre!', array_keys($_GET));
$out = implode('_', $genres);
Here you're filtering out all the parameters that start with genre using preg_grep() and getting a list of parameter names using array_keys().
If you have a URL you need to parse then use this snippet:
$url = 'file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
$genres = preg_grep('!^genre!', array_keys($params));
echo implode('_', $genres);
The difference here is that you use parse_url() to extract the query string and parse_str() to parse the query string.
Output:
genre1_genre4_genre19_genre181
parse_str() with the optional $arr argument is specifically built for exploding a query string properly:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
It can even deal with array arguments.
http_build_query() can glue an array back together with a custom $arg_separator but to get the output specifically as you want it, you will have to manually iterate through the arguments to make the transformation.
You could explode on the '=' then join on '_'.
Related
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
I have a string like this:
$str = '[{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABB0pg6HTwdv7EqUBAAEC","file_size":1347,"file_path":"photos\/file_2.jpg","width":90,"height":75},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABIMbRhad2WVdE6UBAAEC","file_size":17588,"width":320,"height":265},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABHSo-WKlRRfBEaUBAAEC","file_size":18480,"width":330,"height":273}]';
How can I access items in it?
I can use regex to select them, something like /"file_id":"(.*?)"/. But that's not clean at all. Is there any approach to make a array (or an object) of string above?
It's a json string.
You need to decode it with json_decode.
The second argument (true) is to make it an array.
$str = '[{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABB0pg6HTwdv7EqUBAAEC","file_size":1347,"file_path":"photos\/file_2.jpg","width":90,"height":75},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABIMbRhad2WVdE6UBAAEC","file_size":17588,"width":320,"height":265},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABHSo-WKlRRfBEaUBAAEC","file_size":18480,"width":330,"height":273}]';
$arr = json_decode($str, true);
Var_dump($arr);
https://3v4l.org/9BFIC
Explode(“,{”, $str); will work for the above.
You will get array value for each file.
Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc, it can be anything. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?
You can use parse_url and parse_str like this:
$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];
parse_url allows to split an URL in different parts (scheme, host, path, query, etc); here we use it to get only the query (test=123&random=abc). Then we can parse the query with parse_str.
I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:
$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);
the hostname is optional but is required at least the question mark at the begin of parameter string:
$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;
parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );
print_r ( $params );
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.
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()