【发布时间】:2014-05-27 10:08:05
【问题描述】:
我有以下网址:http:example.com/country/France/45。
使用模式http:example.com/country/name/**NUMBER**(?$_GET possibly)。
如何使用正则表达式(或其他的正则表达式)提取数字?
【问题讨论】:
-
\/country\/.*\/([0-9]+) 用 preg_match_all 试试这个
我有以下网址:http:example.com/country/France/45。
使用模式http:example.com/country/name/**NUMBER**(?$_GET possibly)。
如何使用正则表达式(或其他的正则表达式)提取数字?
【问题讨论】:
使用正则表达式:
$str = 'http:example.com/country/France/45';
preg_match('/http:example\.com\/country\/(?P<name>\w+)\/(?P<id>\d+)/', $str, $matches);
print_r($matches); // return array("name"=>"France", "id" => 45);
【讨论】:
$url = 'http:example.com/country/France/45';
$id = end(explode('/',trim($url,'/')));
简单不?
trim ()的用法是去掉尾随的\
【讨论】:
echo $last = substr(strrchr($url, "/"), 1 );
strrchr() 将给出/ 字符的最后一次出现,然后substr() 在它之后给出字符串。
【讨论】:
使用类似的东西
$url = "http://example.com/country/France/45";
$parts = explode('/', $url);
$number = $parts[count($parts) - 1];
如果你最后有 GET 变量,你可以像这样进一步爆炸
$number = explode('?', $number);
$number = $number[0];
希望这会有所帮助:)
【讨论】:
php 的 get 命令是 $_GET 以便显示给数字 do
<html>
<body>
<?php
echo $_GET["eg"];
?>
</body>
</html>
网址为http:example.com/country/name/?eg=**NUMBER**
【讨论】:
使用explode():
$parts = explode('/', $url);
$number = $parts[count($parts)-1];
【讨论】:
/结尾,这将失败!