Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多个带逗号和-(连字符)的分解字符_Php_String_Split_Explode - Fatal编程技术网

Php 多个带逗号和-(连字符)的分解字符

Php 多个带逗号和-(连字符)的分解字符,php,string,split,explode,Php,String,Split,Explode,我想为所有人分解一个字符串: 空白(\n\t等) 逗号 连字符(小破折号)。像这样>>- 但这不起作用: $keywords = explode("\n\t\r\a,-", "my string"); 怎么做?爆炸不能那样做。为此调用了一个很好的函数。这样做: $keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things"); var_dump($keywords); 这将产生: arra

我想为所有人分解一个字符串:

  • 空白(\n\t等)
  • 逗号
  • 连字符(小破折号)。像这样>>-
  • 但这不起作用:

    $keywords = explode("\n\t\r\a,-", "my string");
    

    怎么做?

    爆炸不能那样做。为此调用了一个很好的函数。这样做:

    $keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things");
    var_dump($keywords);
    
    这将产生:

      array
      0 => string 'This' (length=4)
      1 => string 'sign' (length=4)
      2 => string 'is' (length=2)
      3 => string 'why' (length=3)
      4 => string 'we' (length=2)
      5 => string 'can't' (length=5)
      6 => string 'have' (length=4)
      7 => string 'nice' (length=4)
      8 => string 'things' (length=6)
    

    顺便说一句,不要使用拆分,它已被弃用。

    。。。或者,如果您不喜欢正则表达式,但仍希望分解某些内容,则可以在分解之前用一个字符替换多个字符:

    $keywords = explode("-", str_replace(array("\n", "\t", "\r", "\a", ",", "-"), "-", 
      "my string\nIt contains text.\rAnd several\ntypes of new-lines.\tAnd tabs."));
    var_dump($keywords);
    
    这将导致:

    array(6) {
      [0]=>
      string(9) "my string"
      [1]=>
      string(17) "It contains text."
      [2]=>
      string(11) "And several"
      [3]=>
      string(12) "types of new"
      [4]=>
      string(6) "lines."
      [5]=>
      string(9) "And tabs."
    }
    

    此技术在连字符上分解之前,在输入字符串上进行6次遍历(字符串x6的完全遍历)。我将在shamittomar的答案中使用更简单的单函数调用,因为它只对输入字符串进行一次传递。