【问题标题】:PHP preg_split() not capturing the split in the stringPHP preg_split() 未捕获字符串中的拆分
【发布时间】:2012-02-19 03:22:12
【问题描述】:

我正在尝试使用带有 preg_split 的正则表达式将 url 与字符串分开:

    $body = "blah blah blah http://localhost/tomato/veggie?=32";
    $regex = "(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)";
    $url = preg_split($regex, $body);

结果数组是:

    array(2) (
    [0] => (string) blah blah blah 
    [1] => (string))

我想退货:

    array(2) (
    [0] => (string) blah blah blah 
    [1] => (string) http://localhost/tomato/veggie?=32)

不知道我在这里做错了什么...任何建议将不胜感激。

【问题讨论】:

    标签: php regex string preg-split


    【解决方案1】:

    尝试添加另一组括号以使用可选的 preg_split() 参数捕获整个 URL:

    $regex = "((((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+))";
    $url = preg_split($regex, $body, null, PREG_SPLIT_DELIM_CAPTURE);
    

    输出:

    array(5) {
      [0]=>
      string(15) "blah blah blah "
      [1]=>
      string(34) "http://localhost/tomato/veggie?=32"
      [2]=>
      string(7) "http://"
      [3]=>
      string(2) "ht"
      [4]=>
      string(0) ""
    }
    

    【讨论】:

    • 你可以像(((?:(?:f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+))这样添加2个非cature组来清理输出 - 从数组中获取[2][3]:)
    【解决方案2】:

    它失败了,因为您是在 URL 上拆分,而不是在分隔符上。本例中的分隔符是“ftp 或 http 之前的最后一个空格”:

    $body = "blah blah blah http://localhost/tomato/veggie?=32";
    $regex = '/\s+(?=(f|ht)tp:\/\/)/';
    $url = preg_split($regex, $body);
    

    分解正则表达式:

    \s+ - One or more spaces
    (?=...) - Positive look-ahead (match stuff in this group, but don't consume it)
    (f|ht)tp:\/\/ - ftp:// or http://
    

    【讨论】:

    • 如果 URL 后面有一个词,例如 blah blah blah http://localhost/tomato/veggie?=32 test,它将被添加到 URL 的部分中。 array([0]=>'blah blah blah ',[1]=>'http://localhost/tomato/veggie?=32 test')
    • 确实如此。幸运的是,这不适用于这种情况。
    【解决方案3】:

    第一个问题是您的正则表达式不是delimited(即没有被斜线包围)。

    第二个问题是,鉴于您提供的示例输出,您可能需要考虑改用 preg_match

    试试这个,看看是不是你想要的:

    $body = "blah blah blah http://localhost/tomato/veggie?=32";
    $regex = "/^(.*?)((?:(?:f|ht)tps?:\/\/).+)/i";
    preg_match($regex, $body, $url);
    print_r($url);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-05
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2011-06-11
      相关资源
      最近更新 更多