I found a way to get the last part of the url, I just don't know if there's an even better way since I want it to be dynamic.
This is the way I did it:
$url = $_SERVER['REQUEST_URI'];
$categoryName = basename($url);
The last part of the url in this case is always a category(horror for e.g) that's in my database, so the url will always looks like this:
http://localhost:8888/blog/public/index.php/categories/Horror
or
http://localhost:8888/blog/public/index.php/categories/Fantasy
I think you got my point.
Well, the question is, is there a better way or is mine okay? Especially when looking at the
$_SERVER['REQUEST_URI']
Use explode() to split URL by / delimiter and use end() to get last item of array.
$url = "http://localhost:8888/blog/public/index.php/categories/Horror";
$categoryName = #end(explode("/", $url));
// Horror
You can always use a simple regex to get it.
$re = '#.*/(.*)#m';
$str = 'http://localhost:8888/blog/public/index.php/categories/Horror';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo $matches[0][1];
//outputs `Horror`
if you are using laravel or symphony use end(Request::segments())
Related
I need to extract a portion of urls using php. The last 6 segments of the url are the part I need. The first part of the url varies in length and number of directories. So if I have a url like this:
https://www.random.ccc/random2/part1/part2/part3/2017/08/file.txt
or this:
https://www.random.vov/part1/part2/part3/2016/08/file.pdf
What I need is this:
/part1/part2/part3/2017/08/file.txt
or this:
/part1/part2/part3/2016/08/file.pdf
I have tried this:
$string = implode("/",array_slice(explode("/",$string,8),6,4));
which works ok on the first example but not the second. I am not so good with regex and I suppose that is the way. What is the most graceful solution?
Your approach is fine, though adding parse_url in there to isolate just the path will help a lot:
$path = parse_url($url, PHP_URL_PATH); // just the path part of the URL
$parts = explode('/', $path); // all the components
$parts = array_slice($parts, -6); // the last six
$path = implode('/', $parts); // back together as a string
Try it online at 3v4l.org.
Now, to qualify: if you only need the string part of the path, then use parse_url. If, however, you need to work with each of the segments (such as removing only the last six, as asked), then use the common pattern of explode/manipulate/implode.
I have left each of these steps separate in the above so you can debug and choose the parts that work best for you.
Use this, substituting $url as you wish:
$url= "https://www.random.vov/part1/part2/part3/2016/08/file.pdf";
preg_match("%/[^/]*?/[^/]*?/[^/]*?/[^/]*?/[^/]*?/[^/]*?$%", $url, $matches);
echo $matches[0];
best regards!
My webpage has a variable, $currentPage. This is a string of the php token name of the page I'm currently on.
Example: All categories under the user section have names such as:
uAdminNew, uAdminEdit, ect..
I would like for a way to parse out the uAdmin and just determine what is the last word (New and Edit) and call upon functions from there.
I have my navigation system working through these names, therefore I can't change the names or I would to make it easier to parse. Such as adding delimiters.
Is this something only Regex can solve or is there a simpler solution I'm missing? If this is Regex could you explain or provide a link as to how I would go about using it to test against a specific list of strings? I'm very new to it.
For example, so:
$str = 'uAdminEdit';
$ar = preg_match('/([A-Z][^A-Z]+$)/', $str, $m);
echo $m[1]; // Edit
Does the pagename always start with uAdmin? If so, you could split the string by "uAdmin" with explode():
$page = 'uAdminEdit';
echo explode('uAdmin', $page)[1]; //Output: Edit
Or simply remove "uAdmin" with str_replace():
$page = 'uAdminEdit';
echo str_replace('uAdmin', '', $page); //Output: Edit
If you just want the section after uAdmin, use the regex capture groups
preg_match('/uAdmin(.*)/', $sub, $matches);
echo $matches[1]
Getting the value from url which is between the forward slashes. Like
http://localhost/test/manage-users/1230/
output: 1230
I also found some help full answers but they are not satisfy my case properly. Their url is hard coded i.e, their url cant change but in my case url change if user redirect from different pages.
Get the value of a URL after the last slash
Different url when user redirect from different pages.
http://localhost/test/manage-users/1230/?value=1230
http://localhost/test/manage-users/1230/
http://localhost/test/manage-users/1230/test1/?value=1230
So i want a regex which full fill my all cases.
RegEx you need is
\d+(?=\/)
$re = '/\d+(?=\/)/';
$str = 'http://localhost/test/manage-users/1230/?value=1230';
preg_match($re, $str, $matches);
It is working for all three cases you have mentioned.
Check Demo
I don't know if it is possible or not but i have a suggestion. Use URL rewriting.
Feel free to shape your URL's. For example
http://localhost/test/manage-users.php?value=1230
And a little help from this link:
http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/
You can make it look like:
http://localhost/test/manage-users/1230/
You could try the below regex to get the number between slashes,
\/(\d+)\/
DEMO
Your php code would be,
<?php
$re = '~\/(\d+)\/~';
$str = 'http://localhost/test/manage-users/1230/?value=1230';
preg_match($re, $str, $matches);
echo $matches[1];
?> // 1230
I've created my own newsletter module and come across one (big) problem.
The system formats all urls with additional parameters to keep track of the clicks in google analytics.
e.g.
A url like this
http://www.domain.com
becomes like this
http://www.domain.com/&utm_source=newsletter&utm_medium=e-mail&utm_campaign=test
and a url like this
http://www.domain.com/?page=1
becomes like this
http://www.domain.com/?page=1&utm_source=newsletter&utm_medium=e-mail&utm_campaign=test
The first example is bogus. I know the first ampersand has to be replaced by an ampersand and that's where the problem occurs.
I'm using this pattern to extract url's
$pattern = array('#[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%\{\}])*#');
$replace = array('\\0&utm_source=newsletter&utm_medium=e-mail&utm_campaign=test');
$body = preg_replace($pattern,$replace,$body);
Can anybody help me with a correct and working regex, so the first url parameter always contains a questionmark in stead of an ampersand?
just use
if(strpos($string,'?') !== false)
//add with ampersand
else
//add with question mark
Not regex, but it would work. All it does is check for a ? and if it isn't found, change the first & to a question mark.:
$url = (substr_count($url, '?')>0) ? $url : str_replace('&', '?', $url, 1);
A very simple approach would be to look for a string like http://...& where the ... contains no ? question mark or other delimiters:
= preg_replace('#(http://[^\s"\'<>?&]+)&#', '$1?', $src);
But it's probably best if you use a restricted instead of a negated character class:
$src = preg_replace('#(http://[\w/.]+)&#', '$1?', $src);
This solution fixes all urls which have a query beginning with a & (and are missing the ?):
$re = '%([a-zA-Z]+://[^?&\s]+)&(utm_source=newsletter)%';
$body = preg_replace($re, '$1?$2', $body);
I need to extract the first URL from some content. The content may be like this:
({items:[{url:"http://cincinnati.ebayclassifieds.com/",name:"Cincinnati"},{url:"http://dayton.ebayclassifieds.com/",name:"Dayton"}],error:null});
or may contain only a link
({items:[{url:"http://portlandor.ebayclassifieds.com/",name:"Portland (OR)"}],error:null});
currently I have :
$pattern = "/\:\[\{url\:\"(.*)\"\,name/";
preg_match_all($pattern, $htmlContent, $matches);
$URL = $matches[1][0];
however it works only if there is a single link so I need a regex which should work for the both cases.
You can use this REGEX:
$pattern = "/url\:\"([^\"]+)\"/";
Worked for me :)
Hopefully this should work for you
<?php
$str = '({items:[{url:"http://cincinnati.ebayclassifieds.com/",name:"Cincinnati"},{url:"http://dayton.ebayclassifieds.com/",name:"Dayton"}],error:null});'; //The string you want to extract the 1st URL from
$match = ""; //Define the match variable
preg_match("%(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&\%\$#\=~_\-]+))*%",$str,$match); //I Googled for the best Regular expression for URLs and found the one included in the preg_match
echo $match[0]; //Return the first item in the array (the first URL returned)
?>
This is the website that I found the regular expression on: http://regexlib.com/Search.aspx?k=URL
like the others have said, json_decode should work for you aswell
That smells like JSON to me. Try using http://php.net/json_decode
Looks like JSON to me, visit http://php.net/manual/en/book.json.php and use json_decode().