I have a url something like:
www.yourname.mysite.com/templates/diversity/index.php
I need to grab that string, "diversity", and match it against a db value. I've never used anything like preg_match in php, how can I grab that string?
Instead of a regular expression, you can use parse_url() for that:
$url = 'www.yourname.mysite.com/templates/diversity/index.php';
$parts = parse_url($url);
$paths = explode('/', $parts['path']);
// "diversity" is in $paths[1]
For completeness' sake, here's the regular expression:
preg_match('=^[^/]+/[^/]+/([^/]+)/=', $url, $matches);
// "diversity" is in $matches[1]
$ex = explode("/",$_SERVER["PHP_SELF"]);
echo $ex[2];
You can just explode that string and get the third value of the resulting array:
$parts = explode("/", "www.yourname.mysite.com/templates/diversity/index.php");
echo $parts[2]; // diversity
Related
I have below URL in my code and i want to split it and get the number from it
For example from the below URL need to fetch 123456
https://review-test.com/#/c/123456/
I have tried this and it is not working
$completeURL = https://review-test.com/#/c/123456/ ;
list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
Use parse_url
It's specifically made for this sort of thing.
You can do this without using regex also -
$completeURL = 'https://review-test.com/#/c/123456/' ;
list($url, $number) = explode('#c', str_replace('/', '', $completeURL));
echo $number;
If you wan to get the /c/123456/ params you will need to execute the following:
$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
The PHP_URL_FRAGMENT will return a component of the url after #
After parse_url you will end up with a string like this: '/c/123456/'
The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted
In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.
Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)
You should try this: basename
basename — Returns trailing name component of path
<?php
echo basename("https://review-test.com/#/c/123456/");
?>
Demo : http://codepad.org/9Ah83qaP
Subsequently you can directly take from pure regex to fetch numbers from string,
preg_match('!\d+!', "https://review-test.com/#/c/123456/", $matches);
print_r($matches);
Working demo
Simply:
$tmp = explode( '/', $completeUrl).end();
It will explode the string by '/' and take the last element
If you have no other option than regex, for your example data you could use preg_match to split your url instead of preg_replace.
An approach could be to
Capture the first part as a group (.+\/)
Then capture your number as a group (\d+)
Followed by a forward slash at the end of the line \/$/
This will take the last number from the url followed by a forward slash.
Then you could use list and skip the first item of the $matches array because that will contain the text that matched the full pattern.
$completeURL = "https://review-test.com/#/c/123456/";
preg_match('/(.+\/)(\d+)\/$/', $completeURL, $matches);
list(, $url, $number) = $matches;
I need to extract only the 'id' from an URL. The url format is given below. Currently, I use parse_url and substr function, which works. However, it is not a good choice if the length of 'id' changes, where regex comes into play. I am not well-conversant with regex, so I need an idea how to do it in other way e.g. regex.
$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html';
$URLParts = parse_url($url);
// echo $URLParts['path'];
$substring = substr($URLParts['path'],15,8);
echo $substring;
You can use the following regular expression:
preg_match("/.+\/([0-9]+).+/", $url, $matches);
echo $matches[1];
live example
you can use this :
<?php
$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html';
$URLParts = parse_url($url);
$exploded = explode('/',$URLParts['path']);
echo $exploded[2];
?>
I need a regex string to extract parameters from different types of url, for example using $_SERVER["REQUEST_URI"]:
string 1: "/news/page/4" or string 2: "/news/weekly/page/4"
I need to extract the string without last /page/[ID], I mean only /news/page or /news/weekly/, etc.
How can I do it with preg_replace?
Thank you.
You can use explode() instead of regular expressions:
$delimiter = '/';
$parts = explode($delimiter, $_SERVER["REQUEST_URI"]);
$whatINeed = $parts[0] . $delimiter . $parts[1];
regexp solution:
echo preg_replace('/^([\w\W]*)\/page\/\d*/','$1','/news/weekly/page/4');
outputs:
/news/weekly
but you should use explode solution:
$parts = explode('/', $_SERVER["REQUEST_URI"]);
$url = $parts[0].'/'.$parts[1];
You should be able to use: [A-Za-z/]+
But it will be slower then just using substr. EDIT: not substr, but explode.
Try:
$foo = explode('/', $_SERVER["REQUEST_URI"]);
$resultant_url = $foo[0].'/'.$foo[1];
function strip_cdata($string)
{
preg_match_all('/<!\[cdata\[(.*?)\]\]>/is', $string, $matches);
return str_replace($matches[0], $matches[1], $string);
}
I use the above function to extract text from cdata, but I don't know how to modify the reg expression to get a number from the url below.
http://blah.somesite.com/anytextcouldbehere/2828842087.html
Specifically, I need to get "2828842087" from the above url. It will always be numbers and be between the last "/" and ".html".
Thanks
No need to use regexp here:
$url = 'http://blah.somesite.com/anytextcouldbehere/2828842087.html';
$data = parse_url($url);
$number = basename($data['path'], '.html');
Here's the regular expression:
$url = 'http://blah.somesite.com/anytextcouldbehere/2828842087.html';
if( preg_match('#/(\d+)\.html$#', $url, $matches) ){
$number = $matches[1];
}
You can also try this one instead of regex:
$url = 'http://blah.somesite.com/anytextcouldbehere/2828842087.html';
$info = pathinfo($url);
$num = $info['filename'];
echo $num;
use this regex
/\d*/
preg_match_all('/\d*/is', $string, $matches);
you can use this:
preg_match_all('/^http\:\/\/([\w\/\.]+)\/(<?P<num>[\d]+)\.html$/',$url,$matches);
now the number is in $matches['num']. that is an array like this:
Array(0=>2828842087)
good luck
I'm trying to grab the 12345 out of the following URL using preg_match.
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = "http://www.somesite.com/directory/";
$close = "\-";
preg_match("($beg(.*)$close)", $url, $matches);
I have tried multiple combinations of . * ? \b
Does anyone know how to extract 12345 out of the URL with preg_match?
Two things, first off, you need preg_quote and you also need delimiters. Using your construction method:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$beg = preg_quote("http://www.somesite.com/directory/", '/');
$close = preg_quote("-", '/');
preg_match("/($beg(.*?)$close)/", $url, $matches);
But, I would write the query slightly differently:
preg_match('/directory\/(\d+)-/i', $url, $match);
It only matches the directory part, is far more readable, and ensures that you only get digits back (no strings)
This doesn't use preg_match but would achieve the same thing and would execute faster:
$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html";
$url_segments = explode("/", $url);
$last_segment = array_pop($url_segments);
list($id) = explode("-", $last_segment);
echo $id; // Prints 12345
Too slow, I am ^^.
Well, if you are not stuck on preg_match, here is a fast and readable alternative:
$num = (int)substr($url, strlen($beg));
(looking at your code I guessed, that the number you are looking for is a numeric id is it is typical for urls looking like that and will not be "12abc" or anything else.)