简体   繁体   中英

How to get special part of URL using preg_match?

I have an url like this one,

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

What I'm trying to do is get 5b5964935583202d2beff315 and 41 in url.

I really want to know how to do this, and I needs help. Your help would be greatly appreciated!

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

Output:

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

Explanation:

/               : 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
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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