开发者

How do i split string to words and symbols combination array

I do split a sentence to words as followings:

eg.:

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

开发者_StackOverflow中文版result:

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",  
...  
)  

What can be my options in php for it?


Try something like:

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


Wow, that's a tough one! Because you want to keep "," as well. Here is what to do:

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

Note: in the (?<=) and in the (?=), you must put all the characters that you want to be considered as words as well, even if there is no space before and/or after them.


Try this method using 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);


You can try somthing like

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


You can use explode function with delimiter as " " (space) http://php.net/manual/en/function.explode.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜