[英]Cut string from end to specific char in php
我想知道我怎么能切string
在PHP从最后一个字符开始- >到一个特定的字符。 可以说我有以下链接:
www.whatever.com/url/otherurl/2535834
我想要得到2535834
重要说明:数字可以有不同的长度,这就是为什么无论有多少数字,我都想删减/
原因。
谢谢
在这种特殊情况下,使用url可以使用basename()
:
echo basename('www.whatever.com/url/otherurl/2535834');
更通用的解决方案是preg_replace()
,如下所示:
<----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);
模式'#。* /#'使用PCRE regex引擎的默认贪婪性-意味着它将匹配尽可能多的字符,因此在匹配时将使用/abc/123/xyz/
而不是/abc/
图案。
这应该为您工作:
(因此,您可以根据需要获取带斜线或不带斜线的数字)
<?php
$url = "www.whatever.com/url/otherurl/2535834";
preg_match("/\/(\d+)$/",$url,$matches);
print_r($matches);
?>
输出:
Array ( [0] => /2535834 [1] => 2535834 )
$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));
在使用str_replace()
并将针替换为“”之后, strstr()
查找所有内容(包括针str_replace()
如果您的模式是固定的,则可以始终执行以下操作:
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];
这是我的版本:
$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.