【问题标题】:PHP Regex / delimiterPHP 正则表达式/分隔符
【发布时间】:2016-05-27 18:32:53
【问题描述】:

我有一个字符串"/test:n(0-2)/div/",我想通过正则表达式将其拆分为一个带有函数preg_split() 的数组。输出应该是这样的:

output = {
[0]=>"test:n(0-2)"
[1]=>"div"
}

然而,这似乎并不像我想象的那么容易。这是我的尝试:https://regex101.com/r/iP2lD8/1

$re = '/\/.*\//';
$str = '/test:n(0-2)/div/';
$subst = '';

$result = preg_replace($re, $subst, $str, 1);

echo "The result of the substitution is ".$result;

全场比赛 0-17:
/test:n(0-2)/div/

我做错了什么?

【问题讨论】:

    标签: php regex preg-split


    【解决方案1】:

    只需使用explode():

    $result = array_filter(explode('/', $string));
    

    array_filter() 从两端的/ 中删除空。或者你可以trim()它:

    $result = explode('/', trim($string, '/'));
    

    但要回答这个问题,您只需使用/ 作为preg_split() 的模式,或者像/\// 那样转义/,或者使用不同的分隔符:

    $result = array_filter(preg_split('#/#', $string));
    

    另一种方式取决于你的需要和字符串内容的复杂程度:

    preg_match_all('#/([^/]+)#', $string, $result);
    print_r($result[1]);
    

    $result[0] 是完全匹配的数组,$result[1] 是第一个捕获组 () 的数组。如果有更多的捕获组,您将在 $result 中拥有更多的数组元素。

    【讨论】:

    • 不工作,结果是:Array ( [1] => table [2] => tr:n(1-2) )
    • 第二个选项同样的问题:/
    【解决方案2】:

    你可以使用

    '~/([^/]+)~'
    

    请参阅regex demo。此模式匹配 /,然后将除 / 之外的 1 个或多个字符捕获到第 1 组中。

    您遇到的问题是尾部斜杠已被消耗。另外,您使用了贪婪匹配,这只是抓住了太多。

    Ideone demo:

    $re = '~/([^/]+)~'; 
    $str = "/test:n(0-2)/div/"; 
    preg_match_all($re, $str, $matches);
    print_r($matches[1]);
    // => Array  ( [0] => test:n(0-2) [1] => div  )  
    

    【讨论】:

    • 为什么要保存到$matches[1]?我本来希望在 $matches[0] 中出现第一次,在 $matches[1] 中出现第二次
    • 这取决于你有多少零件。总是只有2吗?那么'~/([^/]+)/([^/]+)~' 可以提供帮助。见this demo
    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多