简体   繁体   English

PHP preg_match在文本和第一次出现之间-

[英]PHP preg_match between text and the first occurrence of -

I'm trying to grab the 12345 out of the following URL using preg_match. 我正在尝试使用preg_match从以下URL中提取12345。

$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);

I have tried multiple combinations of . 我尝试了的多种组合。 * ? *? \\b \\ b

Does anyone know how to extract 12345 out of the URL with preg_match? 有谁知道如何使用preg_match从URL中提取12345?

Two things, first off, you need preg_quote and you also need delimiters. 首先,需要两件事,即需要preg_quote和分隔符。 Using your construction method: 使用您的构造方法:

$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);

But, I would write the query slightly differently: 但是,我会稍微不同地编写查询:

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

It only matches the directory part, is far more readable, and ensures that you only get digits back (no strings) 它仅与目录部分匹配,可读性更强,并确保您只返回数字(没有字符串)

This doesn't use preg_match but would achieve the same thing and would execute faster: 这不使用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

Too slow, I am ^^. 太慢了,我是^^。 Well, if you are not stuck on preg_match, here is a fast and readable alternative: 好吧,如果您不喜欢preg_match,这里是一种快速且易读的选择:

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

(looking at your code I guessed, that the number you are looking for is a numeric id is it is typical for urls looking like that and will not be "12abc" or anything else.) (查看我猜到的代码,您要查找的数字是一个数字ID,对于类似这样的url通常是这样,并且不会是“ 12abc”或其他任何形式。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM