【问题标题】:How do i split string to words and symbols combination array如何将字符串拆分为单词和符号组合数组
【发布时间】:2011-06-22 06:18:27
【问题描述】:

我确实将一个句子分成以下几个词:
例如:

This is a test from php, python, asp and also from other languages. Alash! i cannot get my output as followings.  

结果:

array(  
[0]=>"This",  
[1]=>"is",  
[2]=>"a",  
[3]=>"test",  
[4]=>"from",  
[5]=>"php",  
[6]=>",",  
[7]=>"python",  
[8]=>",",  
[9]=>"asp",  
[10]=>"and",  
[11]=>"also",  
[12]=>"from",  
[13]=>"other",  
[14]=>"languages",  
[15]=>".",  
[16]=>"Alash",  
[17]=>"!",  
[18]=>"I",  
[19]=>"cannot",  
[20]=>"get",  
...  
)  

我在 php 中可以有哪些选择?

【问题讨论】:

    标签: php regex split


    【解决方案1】:

    尝试类似:

    preg_split('/\s+|\b/', $string)
    

    【讨论】:

    • 那是 gr8... 也希望跳过空格
    • 最好使用/\s+|\b(?=\W)/,这样你就不会得到所有这些空字符串。
    • 你得到了这个空间?当我尝试在 Perl 中拆分时,我没有。 perl -e "print join'#', split /\s+|\b/, 'foo, bar baz! k'" 给了我foo#,#bar#baz#!#k,没有任何空格。我猜 PHP 拆分的工作方式不同。
    【解决方案2】:

    哇,好难啊!因为您也想保留“,”。这是做什么:

    $string = "I beg to differ, you can get it as the previous.";
    $words = preg_split('/\s+|(?<=[,\.!\?])|(?=[,\.!\?])/',$string);
    

    注意:在(?&lt;=)(?=) 中,您必须将所有您想被视为单词的字符也放入其中,即使它们之前和/或之后没有空格。

    【讨论】:

      【解决方案3】:

      使用 Explode 试试这个方法

      function multiexplode ($delimiters,$string) 
      {
      
          $ready = str_replace($delimiters, $delimiters[0], $string);
          $launch = explode($delimiters[0], $ready);
          return  $launch;
      }
      
      $text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
      
      $exploded = multiexplode(array(",",".","|",":"),$text);
      
      print_r($exploded);
      

      【讨论】:

        【解决方案4】:

        你可以试试

        $res =  preg_split( '/ |([.,])/' , $string,-1, PREG_SPLIT_DELIM_CAPTURE| PREG_SPLIT_NO_EMPTY);
        

        【讨论】:

          【解决方案5】:

          您可以使用带有分隔符的分解功能作为“”(空格) http://php.net/manual/en/function.explode.php

          【讨论】:

            猜你喜欢
            • 2011-10-23
            • 1970-01-01
            • 2010-09-26
            • 2011-09-24
            • 1970-01-01
            • 2022-08-12
            • 2012-11-16
            相关资源
            最近更新 更多