开发者

PREG_ or Regex Question

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; 


This should work

    $str = "example.com/123-test";
    preg_match("/\/([\d]{1,4})-[^\/]+$/", $str, $matches);
    echo $matches[1]; // 123

It makes sure that the ###-word part is at the end and that there are only 1-4 digits.


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 with preg_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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜