Reputation: 14773
I would like to know how I can cut a string
in PHP starting from the last character -> to a specific character. Lets say I have following link:
www.whatever.com/url/otherurl/2535834
and I want to get 2535834
Important note: the number can have a different length, which is why I want to cut out to the /
no matter how many numbers there are.
Thanks
Upvotes: 0
Views: 269
Reputation: 157967
In this special case, an url, use basename()
:
echo basename('www.whatever.com/url/otherurl/2535834');
A more general solution would be preg_replace()
, like this:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/
instead of just /abc/
when matching the pattern.
Upvotes: 1
Reputation: 593
Here's mine version:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));
Upvotes: 0
Reputation: 11859
if your pattern is fixed you can always do:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
Upvotes: 0
Reputation: 12197
With strstr() and str_replace() in action
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
strstr()
finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()
Upvotes: 0
Reputation: 59681
This should work for you:
(So you can get the number with or without a slash, if you need that)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
Output:
Array ( [0] => /2535834 [1] => 2535834 )
Upvotes: 0
Reputation: 23958
Use
<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>
Upvotes: 0