2011-02-07 111 views
0

我试图用preg_match从以下URL中获取12345。文本和第一次出现之间的PHP preg_match -

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$beg = "http://www.somesite.com/directory/"; 
$close = "\-"; 
preg_match("($beg(.*)$close)", $url, $matches); 

我试过了多种组合。 *? \ b

有谁知道如何从preg_match中提取12345的URL吗?

回答

3

有两件事,首先,你需要preg_quote,你也需要分隔符。使用您的施工方法:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$beg = preg_quote("http://www.somesite.com/directory/", '/'); 
$close = preg_quote("-", '/'); 
preg_match("/($beg(.*?)$close)/", $url, $matches); 

不过,我会写查询略有不同:

preg_match('/directory\/(\d+)-/i', $url, $match); 

它只目录部分匹配的,是更具可读性,并确保你只能得到数字后面(无弦)

+0

谢谢,完美的作品! – Mark 2011-02-07 20:17:15

1

这不使用的preg_match,但会达到同样的事情,会执行得更快:

$url = "http://www.somesite.com/directory/12345-this-is-the-rest-of-the-url.html"; 

$url_segments = explode("/", $url); 
$last_segment = array_pop($url_segments); 

list($id) = explode("-", $last_segment); 

echo $id; // Prints 12345 
+0

实际上,运行速度并不快,那么ircmaxell提供的代码片段(至少不是可测量的数量)。在我的测试过程中,有时候你的片段,有时候ircmaxell的片段会更快。尽管如此,我的片段几乎快了一倍。 – yankee 2011-02-07 20:23:05

+0

@yankee,感谢您为测试和分享结果所做的努力! – 2011-02-07 20:26:50

0

太慢了,我是^^。 好吧,如果你不停留在的preg_match是,这里是一个快速和可读性的选择:

$num = (int)substr($url, strlen($beg)); 

(看你的代码,我猜,你正在寻找的号码是数字ID是它是典型的看起来像这样的网址,不会是“12abc”或其他任何东西。)

相关问题