代码之家  ›  专栏  ›  技术社区  ›  JasonGenX

php regex似乎不像预期的那样工作

  •  -1
  • JasonGenX  · 技术社区  · 8 年前

    字符串:

    https://fakedomain.com/2017/07/01/the-string-i-want-to-get/

    代码:

    $url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
    $out = [];
    
    preg_match('\/\d{4}\/\d{2}\/\d{2}(.*)', $url, $out);
    
    // At this point $out is empty... 
    
    // Also...  I tried this (separately)
    
    $keywords = preg_split("\/\d{4}\/\d{2}\/\d{2}(.*)", $url);
    // also $keywords is empty... 
    

    我已经对regex进行了外部测试,它可以工作。我想把 /the-string-i-want-to-get/ 字符串。我做错什么了?

    3 回复  |  直到 8 年前
        1
  •  2
  •   David Lemon amitgoyal    8 年前

    我不会用正则表达式。在这种情况下,最好使用 parse_url 还有其他一些帮手喜欢 trim 和 explode .

    <?php    
    $url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
    
    $parsed = parse_url($url);
    $Xploded = explode('/',trim($parsed['path'],'/'));
    print $Xploded[count($Xploded)-1];
    
    // outputs: the-string-i-want-to-get
    
        2
  •  1
  •   AbraCadaver    8 年前

    有一个功能:

    echo basename($url);
    
        3
  •  0
  •   Praveen Kumar Purushothaman    8 年前

    preg_split
    用正则表达式拆分字符串。用正则表达式拆分给定字符串。

    你的 $url 将按日期分割。你不需要这样做:

    <?php
      $url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
      $out = [];
      preg_match('/\/\d{4}\/\d{2}\/\d{2}(.*)/', $url, $out); 
      // See here...
      var_dump($out);
    

    您将得到一个包含两个元素的数组:

    array(2) {
      [0]=>
      string(37) "/2017/07/01/the-string-i-want-to-get/"
      [1]=>
      string(26) "/the-string-i-want-to-get/"
    }