douque9815 2014-04-03 19:23
浏览 139
已采纳

Php pcre正则表达式 - 用反斜杠分割文本

I need this string: "test1 test2-test3\test4" to be split into 4 strings:

Array
(
    [0] => test1
    [1] => test2
    [2] => test3
    [3] => test4
)

What am I doing wrong?

I've tried this:

<?php

    $aa = 'test1 test2-test3\test4';
    $arr = preg_split('#[\s|\|-]+#u', $aa);
    print_r($arr);

?>
Array
(
    [0] => test1
    [1] => test2
    [2] => test3\test4
)

And this:

<?php

    $aa = 'test1 test2-test3\test4';
    $arr = preg_split('#[\s|\\|-]+#u', $aa);
    print_r($arr);

?>
Array
(
    [0] => test1
    [1] => test2
    [2] => test3\test4
)

To no avail. For some reason it doesn't split by backslash- why?

  • 写回答

5条回答 默认 最新

  • dongye1143 2014-04-03 19:24
    关注

    Try three slashes \:

        $arr = preg_split('#[\s|\\\|-]+#u', $aa);
    

    And you don't need the alternation in the character class:

        $arr = preg_split('#[\s\\\-]+#u', $aa);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?