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

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

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块