preg_match - extracting string from url - php

I've got an URL's like this:
http://localhost/adminator/index.php?section=1portal&tool=2firmy
and
http://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26
and I want to be able to extract the SECTION and TOOL parameters.
I've came up with this:
preg_match('/(.*)(section=)(.*)(&tool=)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];
But this works only for the first URL, not the second, and than I have this:
preg_match('/(.*)(section=)(.*)(&tool=)(.*)(&)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];
And this only works for the second url, not the first.
How can I make it work in both cases? Thanks.

$url = 'http://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26';
$url = parse_url($url, PHP_URL_QUERY);
parse_str($url, $output);
echo $output['section']; // 1portal
echo $output['tool']; // 2firmy

Can't you just use $_GET['section'] and $_GET['tool']?

'section=(.+?).*?&tool=(.+?)' should work, then check group 1 and 2 for the value

Related

PHP Parse URL From Current URL

I am trying to parse url and extract value from it .My url value is www.mysite.com/register/?referredby=admin. I want to get value admin from this url. For this, I have written following code. Its giving me value referredby=admin, but I want only admin as value. How Can I achieve this? Below is my code:
<?php
$url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
setcookie('ref_by', parse_url($url, PHP_URL_QUERY));
echo $_COOKIE['ref_by'];
?>
You can use parse_str() function.
$url = "www.mysite.com/register/?email=admin";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
Try this code,
$url = "www.mysite.com/register/?referredby=admin";
$parse = parse_url($url, PHP_URL_QUERY);
parse_str($parse, $output);
echo $output['referredby'];
$referred = $_GET['referredby'];
$referred = "referredby=admin";
$pieces = explode("=", $referred);
echo $pieces[1]; // admin
I don't know if it's still relevant for you, but maybe it is for others: I've recently released a composer package for parsing urls (https://www.crwlr.software/packages/url). Using that library you can do it like this:
$url = 'https://www.example.com/register/?referredby=admin';
$query = Crwlr\Url\Url::parse($url)->queryArray();
echo $query['referredby'];
The parse method parses the url and returns an object, the queryArray method returns the url query as array.
Is not a really clean solution, but you can try something like:
$url = "MYURL";
$parse = parse_url($url);
parse_str($parse['query']);
echo $referredby; // same name of the get param (see parse_str doc)
PHP.net: Warning
Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.
Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.
Read section on security of Using Register Globals explaining why it is dangerous.

How do I Set PHP Variables from URL Encoded Parameters?

Ok guys I got a situation here and I could use some help.
I get the parameters sent to me url encoded and they look like this
http://example.com/tyntec.php?sender%3D%2B16155305760%26receiver%3D%2B17874539876%26text%3Dplease+stop+sending+messages
I am trying to set my variables like this but that is not working because I guess the $_REQUEST is skipping the encoded & sign
$to = $_REQUEST['receiver'];
$from = $_REQUEST['sender'];
$text = $_REQUEST['text'];
How do I properly grab the parameters from the URL and set the variables?
Thanks in advance for helping me out.
Try this.
parse_str( urldecode( 'http://example.com/tyntec.php?sender%3D%2B16155305760%26receiver%3D%2B17874539876%26text%3Dplease+stop+sending+messages' ), $output );
var_dump($output);
Use this:
<?php
$url = 'http://example.com/tyntec.php?sender%3D%2B16155305760%26receiver%3D%2B17874539876%26text%3Dplease+stop+sending+messages
';
$url = utf8_decode(urldecode($url));
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['sender'];
echo $query["receiver"];
echo $query["text"];
?>

Replace url paramer by using php

I have a url & its structure like
https://www.example.com/i/location-name/category/subcategory/item/item-id
I want to replace the url parameter(location-name) dynamically by new parameter using PHP.
Modified url is looks like this
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
I had successfully done with query parameters by using http_build_query();
But in this case i had tried with preg_replace(), but its not working
Thanks
If you would like to use regex.
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
print preg_replace('|/location-name/|','/'.$new_param.'/',$url);
I don't recommend search for only location-name (without slash) beacause it will match with for example location-names string.
UPDATE
Based on placement not string you can change that part that way:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
$new_param = 'another-parameter';
$new_url = preg_replace('|/i/(.*?)/|','/i/'.$new_param.'/',$url);
print $new_url.'<br/>';
You will get:
https://www.example.com/i/new-parameter/category/subcategory/item/item-id
https://www.example.com/i/another-parameter/category/subcategory/item/item-id
Alternative solution
If you would like to be sure about change, you can do it another way, something like this:
$url = 'https://www.example.com/i/location-name/category/subcategory/item/item-id';
$new_param = 'new-param';
$parts = parse_url($url);
$path_parts = explode('/',$parts['path']);
$path_parts[2] = $new_param;
$new_path = implode('/',$path_parts);
$new_url = $parts['scheme'].'://'.$parts['host'].$new_path;
print( $new_url);
Try this one:
$new_url = str_replace('location-name', 'my-location', 'https://www.example.com/i/location-name/category/subcategory/item/item-id')

PHP: str_replace within a word/phrase

I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.
Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90
This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;
$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);

Get some value from url?

I have this kind of url from youtube, with the value of video
$url='http://www.youtube.com/watch?v=H_IkPia6eBA&';
What i need is just to get new string with value of V etc in this case
$newstring='H_IkPia6eBA&';
I dont know how long V could be, only i need to get that value of V, I have tried
$string = 'http://www.youtube.com/watch?v=oYyslNuRcwM';
$url = parse_url($string);
parse_str($url['query'], $query);
print_r($query);
Tried with this, but in CodeIgniter post, I only get empty array?
You're almost there already.
<?php
$string = 'http://www.youtube.com/watch?v=oYyslNuRcwM';
$url = parse_url($string);
parse_str($url['query'], $query);
$newstring=$query["v"]; // just this line is missing
echo $newstring;
?>
Demo
But you know something? If the url format is always going to be like that then no need for all those functions. It then can simply be
<?php
$url='http://www.youtube.com/watch?v=H_IkPia6eBA&';
echo str_replace("http://www.youtube.com/watch?v=","",$url);
?>

Categories