PREG_ 或正则表达式问题
我想匹配 /
的最后一个实例(我相信您使用 [^/]+$
)并复制接下来的四个或更少数字的内容,直到我到达破折号-
。
我相信返回这个数字的“正确”方法是通过 preg_split,但我 没有把握。我知道的唯一其他方法是在 /
上爆炸,数组反转,在 -
上爆炸,分配。我确信还有更优雅的方式吗?
例如,
example.com/12-something // get 12
example.com/996-something // get 996
example.com/12345-no-deal // return nothing
不幸的是,我不像你们中的一些人那样是正则表达式专家。
这是做同样事情的一种丑陋的方法。
$strip = array_reverse(explode('/', $page));
$strip = $strip[0];
$strip = explode('-', $strip);
$strip = $strip[0];
echo (strlen($strip) < 4) ? (int)$strip : null;
I'd like to match the last instance of /
(I believe you use [^/]+$
) and copy the contents of the next four or less numbers until I get to a dash -
.
I believe the "right" method to return this number is through a preg_split, but I'm
not sure. the only other way I know is to explode on /
, array reverse, explode on -
, assign. I'm sure there's a more elegant way though?
For instance
example.com/12-something // get 12
example.com/996-something // get 996
example.com/12345-no-deal // return nothing
I'm unfortunately not a regex guru like some of you folks though.
Here is an ugly way to do the same thing.
$strip = array_reverse(explode('/', $page));
$strip = $strip[0];
$strip = explode('-', $strip);
$strip = $strip[0];
echo (strlen($strip) < 4) ? (int)$strip : null;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该有效,
它确保
###-word
部分位于末尾,并且只有 1-4 位数字。This should work
It makes sure that the
###-word
part is at the end and that there are only 1-4 digits./\/(\d{1,4})-[^\/]+$/
上的匹配应该与第一个捕获变量中的数字相符。抱歉,我不写 PHP,也不想处理preg_match
的接口,但这就是正则表达式。如果现在 PHP 支持非斜杠正则表达式分隔符,那么
m#/(\d{1,4})-[^/]+$#
是使用牙签较少的版本。A match on
/\/(\d{1,4})-[^\/]+$/
should fit the bill with the number in the first capture var. My apologies, I don't write PHP and I don't want to deal withpreg_match
's interface, but that's the regex anyhow.If PHP supports non-slash regex delimiters these days,
m#/(\d{1,4})-[^/]+$#
is the version with fewer leaning-toothpicks.