使用PHP从URL提取ID或特定部分

时间:2019-05-25 07:52:27

标签: php laravel

我想从URL中提取id,就像URL是https://www.themoviedb.org/movie/49730-red-riding-hood?language=en-US 它应该像$id = 49730

1 个答案:

答案 0 :(得分:1)

您在寻找这个吗?

$url = 'https://www.themoviedb.org/movie/49730-red-riding-hood?language=en-US';

$urlFromBrowser = $_SERVER['HTTP_HOST']; // or you can get the url from the browser

$id = preg_split('#([0-9]+)#', $url, null, PREG_SPLIT_DELIM_CAPTURE)[1];

echo $id;

// ALTERNATIVE REGEX

$id2 = str_replace('-', '', preg_split('#([0-9]+[-]{1})#', $url, null, PREG_SPLIT_DELIM_CAPTURE)[1]); // this REGEX takes in case the '-' after the number so it can be better to check with this one if the URL might contain multiple numbers at different positions

echo $id2;