【问题标题】:regex code preg_split (:)正则表达式代码 preg_split (:)
【发布时间】:2016-10-17 16:54:31
【问题描述】:

对于以下代码:

$string = "hello: Mister, Winterbottom";

$words = preg_split("/[\s,]+/", $string);
print_r ($words);

我明白了:

Array ( [0] => hello: [1] => Mister [2] => Winterbottom )

但我希望结果是:

Array ( [0] => hello [1] => Mister [2] => Winterbottom )

这样它就会忽略冒号。我该怎么做?

【问题讨论】:

  • 使用/[\s,:]+/。或/\W+/

标签: php arrays regex string


【解决方案1】:

如果你需要用:扩展你的字符类,只要把它放在里面并使用

/[\s,:]+/

its demo here。或者,只需使用/\W+/ 与 1+ 非单词字符进行拆分。

$words = preg_split("/[\s,:]+/", $string);
print_r ($words);
// Or
print_r(preg_split("/\W+/", $string));

PHP demo

【讨论】:

    【解决方案2】:
    $string = "hello: Mister, Winterbottom";
    
    $words = preg_split("/[\s,]+/", $string);
    
    $words[0] = rtrim($words[0],":");
    
    print_r ($words);
    

    【讨论】:

    • 答案应该有解释。
    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多