【问题标题】:PHP split URL path string into just 2 string componentsPHP 将 URL 路径字符串拆分为 2 个字符串组件
【发布时间】:2013-06-13 16:36:12
【问题描述】:

我有一个 URL,例如 $url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html'。我想采取路径并将结尾分成两个变量:一个包含数字(48),一个包含数字之后的所有内容(chicken-broccoli-ham)。

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

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

$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 = ???;

【问题讨论】:

  • 所以您希望结果为 [48, chicken broccoli ham] 或 [monkey 48, chicken broccoli ham]?
  • 感谢结果为 48,鸡肉西兰花火腿

标签: php arrays string url path


【解决方案1】:
$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
preg_match("/([0-9]+)[-](.+)\.html$/",$url,$matches);

$matches[1] 包含数字

$matches[2] 包含“chicken-broccoli-ham”

【讨论】:

    【解决方案2】:
    <?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,您将获得网址的路径部分 (monkey-48-chicken-broccoli-ham.html),然后只需按数字拆分字符串。

    注意:需要去掉开头的 - 和结尾的 .html 才能达到你想要的效果。

    【讨论】:

      【解决方案3】:

      试试这个:

      <?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)
      
      ?>
      

      【讨论】:

      • 非常感谢。我知道这很容易。我显然错过了手册中的 preg_match!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2012-02-22
      • 2017-06-27
      相关资源
      最近更新 更多