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
Related
I need to get the last three parts of a string (url). No need to pull the url from the browser as I already grab it from the database.
So, the string looks like: www.mysite.com/uploads/09/03/myimage.png
The part I'd like to extract from the string is "09/03/myimage.png"
<?php
$url="www.mysite.com/uploads/09/03/myimage.png";
$values=explode("/",$url); // this will split url string to array based on "/"char
$length=sizeof($values); //calculated array length
$lastthreeStringsCombined=$values[$length-3].'/'.$values[$length-2].'/'.$values[$length-1]; // formed new string by combining last 3 array elements
echo $lastthreeStringsCombined;
?>
Try this:
$lastThreeParts = implode('/', array_slice(explode('/', $url), -3, 3, true));
I'm assuming you want to pull out just the path part and ignore query parameters or hash values in the URL.
I would suggest using parse_url() (documented here: http://php.net/manual/en/function.parse-url.php) to pull out the path.
$url = 'www.mysite.com/uploads/09/03/myimage.png';
$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$output = array_slice($parts, -3, 3);
var_dump($output);
This will provide you with an array of the last 3 parts of the path and handles cases like query strings and hash values in the array, of course you will still need to do basic length validation to ensure this logic still holds.
I have the following string whose contents will vary but structure will always be the same
Tree_Group&lang=&discussionID=1012&t=viewDiscussion
How can I extract discussionID from it? No matter how long or short it may be
E.g. 6745
preg_match('/discussionID=([^&]+)/', $your_string, $matches);
$matches[1] should contain your ID.
You can extract it with parse_str:
// strip out "Tree_Group&"
$str = str_replace("Tree_Group&", "", "Tree_Group&lang=&discussionID=1012&t=viewDiscussion");
// parse string as if it we a url query string (putting results into output)
parse_str($str, $output);
// get discussionID
$discussionID = $output["discussionID"];
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()
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 '_'.
I have a string which looks something like this:
$fetched = name=myName zip=420424 country=myCountry;
// and so on, it is not an array
I fetch these values from an api.
I want only the zip=873289 (infact only the numbers).
So I use:
// $fetched above is the output of the function below
$fetched = file_get_contents("http://example.com");
This way I fetch the contents and can match it with this code
$zip = preg_match ('/zip=[0-9]+/', $fetched );
But I want to store it in the variable, what is function to store the matched results?
You need to indicate the part you want to capture with parentheses, then supply an extra parameter to preg_match to pick these up:
$matches=array();
if (preg_match ('/zip=([0-9]+)/', $fetched, $matches ))
{
$zip=$matches[1];
}
preg_match() stores its result in the third argument, which is passed by reference. So instead of:
$zip = preg_match ('/zip=[0-9]+/', $fetched);
You should have:
preg_match ('/zip=[0-9]+/', $fetched, $zip);