如何使用preg_match获得URL的特殊部分?

时间:2018-11-09 15:41:57

标签: php regex string preg-match

我有一个这样的网址,

https://example.com/folder-name/article-name-xxx-xxx-xxx-xxx-xxx-xxx-5b5964935583202d2beff315.html#id-41

我想做的是在URL中获得 5b5964935583202d2beff315 41

我真的很想知道该怎么做,我需要帮助。您的帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

$url = "https://example.com/folder-name/dien-hy-cong-luoc-story-of-yanxi-palace-5b5964935583202d2beff315.html#id-41";

preg_match("/^.+-([^.-]+)\.html#id-(\d+)/", $url, $matches);
print_r($matches);

输出:

Array
(
    [0] => https://example.com/folder-name/dien-hy-cong-luoc-story-of-yanxi-palace-5b5964935583202d2beff315.html#id-41
    [1] => 5b5964935583202d2beff315
    [2] => 41
)

说明:

/               : regex delimiter
  ^             : beginning of line
    .+          : 1 or more any character but newline
    -           : a dash
    ([^.-]+)    : group 1, 1 or more any character that is not a dot or dash
    \.          : a dot
    html#id-    : literally 
    (\d+)       : group 2, 1 or more digits
/