使用Preg_match检查号码ID


Check number ID with Preg_match

我有一个小问题。

我想检查一下这样的帖子的编号:

http://xxx.xxxxxx.net/episodio/168

这是我代码的一部分,只需要检查号码:

[...]
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/[0-9]',trim($url))){
[...]

能帮我吗?谢谢

如果您想使用preg_match:

$url = 'http://horadeaventura.enlatino.net/episodio/168';
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/([0-9]+)#',trim($url), $matches)){
    $post = $matches[1];
    echo $post;
}

所以,基本上:我添加了一个结束分隔符(#),将"[0-9]"更改为"([0-9])+",添加了",$matches"来捕获匹配项。当然,使用preg_match之外的其他选项可以做得更好。但我想让你的代码片段发挥作用,而不是重写它。

如果你不想使用preg_match(),你可以进行

$string = "http://xxx.xxxxxx.net/episodio/168";
$array = explode("/", $string);
echo end($array);

将输出

168

这是假设您要查找的数字始终是url字符串的最后一部分

或者,您可以在最后一个位置检查的数字

if(preg_match('#[0-9]+$#',trim($url),$match)){
print_r($match);
}