预匹配URL中的最后一个字符串(_Match)


Preg_Match Last String From A URL

我想做的是使用preg_match 从web url中获取分页

示例:http://www.google.com/page/223

我需要从这个网址是"223"

我尝试了这个代码,但不起作用。。。

preg_match('~"http://www.google.com/page/(.*)"~iU', 'http://www.google.com/page/223', $page);
print_r($page);

第一路

preg_match("/[^'/]+$/", "http://www.google.com/page/223", $matches);
$last_word = $matches[0]; // 223

第二路

substr(strrchr(rtrim($url, '/'), '/'), 1)

第三路

$ex = explode("/",$_SERVER["PHP_SELF"]);
      echo end($ex); 

为什么在模式中使用"?字符串中没有引号。此外,U也是错误的。

应该是:

preg_match('~http://www.google.com/page/(.*)~', 'http://www.google.com/page/223', $matches);
echo $page = $matches[1];

不需要regex或爆炸,只需使用字符串函数:

$url = "http://www.google.com/page/223";
$lastPart = substr($url, strrpos($url, "/")+1); // +1 to move 1 past the /

如果你想让它更安全(例如"/page/"必须存在):

$url = "http://www.google.com/page/223";
$lastPart = substr($url, strrpos($url, "/page/")+6); // +6 to move 1 past the '/page/'
if($lastPart===false){ $lastPart = 0; echo "Not found";}

总是尝试使用字符串函数而不是正则表达式/数组函数,字符串函数要快得多。