PHP 将 URL 路径字符串拆分为仅 2 个字符串组件


PHP split URL path string into just 2 string components

我有一个网址,比如说,$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html'。我想采用路径并将末端拆分为两个变量:一个包含数字 (48(,另一个包含数字之后的所有内容(鸡肉-西兰花-火腿(。

虽然我可以将下面的代码中返回的数组分成单独的单词,但问题是,我不知道数字后面会有多少个单词。

所以我的问题是,如何将路径拆分为"数字"和"数字之后的所有内容"以将它们存储为变量?这是我到目前为止所拥有的:

$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$parsedUrl = parse_url($url);
$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$tag = end($parts);
$tag1 = str_replace("-", " ", $tag);  //replace - with spaces
$tag2 = str_replace(".html", "", $tag1);//delete the ".html" off the end
$tag3 = str_replace("monkey", "", $tag2); //delete the "monkey" word.

这是我需要帮助的地方:

$number = ???;
$wordstring = ???;
$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
preg_match("/([0-9]+)[-](.+)'.html$/",$url,$matches);

$matches[1] 包含数字

$matches[2]含有"鸡肉-西兰花-火腿">

试试这个:

<?php
$url = 'https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$path = basename($url, ".html");
$path = str_replace("-", " ", $path);
preg_match("/('d+)'s+(.*)/", $path, $match);
echo $match[1] // 48 (number)
echo $match[2] // word after number (chicken broccoli ham)
?>
<?php
$url = 'https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$path = parse_url($url, PHP_URL_PATH);
$parts = preg_split('/[0-9]+/', $path);

使用parse_url,您可以获得URL的路径部分(猴子-48-鸡-西兰花-火腿.html(,然后简单地按数字拆分字符串。

注意:您需要删除开头的-和结尾的.html才能达到所需的结果。