PHP – Split sentence into words

Q.) Ignore ‘Spaces’ and split sentence into words and store into array

Function:

<?php
function splitIt($s){
			$arr = array('.',',');
			$s = str_replace($arr," ",$s);
			$s = preg_replace("/( )+/", " ", $s);
			$s = preg_replace("/^( )+/", "", $s);
			$s = preg_replace("/( )+$/", "", $s);
			$tokens = explode(" ",$s);
			return $tokens;
		}
?>

Input:

 <?php
 $answer = splitIt("   hello world. prt this sentence,please  ");
 print_r($answer);
?>

Output:

 Array ( 
    [0] => hello
    [0] => world
    [0] => prt
    [0] => this
    [0] => sentence
    [0] => please
)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s