如何将字符串拆分为单词和符号组合数组

时间:2011-06-22 06:18:27

标签: php regex split

我将一句话分成如下句子:
例如:

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中的选项吗?

5 个答案:

答案 0 :(得分:2)

尝试类似:

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

答案 1 :(得分:2)

哇,这太难了!因为你想保持“,”。这是做什么:

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

注意:在(?<=)(?=)中,您必须将您想要的所有字符也视为字词,即使在它们之前和/或之后没有空格也是如此

答案 2 :(得分:2)

使用爆炸

尝试此方法
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);

答案 3 :(得分:1)

您可以尝试类似

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

答案 4 :(得分:0)

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