[英]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.