Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to extract words from a string.
For example if the string is
$str = "It is a hot day";


I want to get the five words in this string as array
$word[0] = 'It';
$word[1] = 'is';
$word[2] = 'a';
$word[3] = 'hot';
$word[4] = 'day';

I have used the explode function to achieve my purpose like this
$str = "It is a hot day";
$word = explode(" ",str);


It works fine until the number of spaces between or after the words is one. But if the number of spaces or more than one between or after any word, it get that space as a word.
For example if the string is
$str = "It is  a hot day";

Now, It has two spaces between 'is' and 'a'. So, when I convert it into array using explode function, it will give me six number of elements not five.
So, I want only words values in my array not any space as array value. How can I do that?
Posted
Updated 5-Dec-11 18:05pm
v2

You can use preg_split[^] to split the string using a regular expression:

$word = preg_split('/\s+/',$str);
 
Share this answer
 
 
Share this answer
 
Comments
rashidfarooq 6-Dec-11 0:35am    
Probably, you have not read my question deeply. My problem is not to extract only the words from string but also avoid blank spaces from being extracted as words. Plz review my question.
My solution is not there in this article that you referred.
You might write yourself a simple function to perform the task. It would be (at least) a useful exercise.
 
Share this answer
 
Comments
rashidfarooq 8-Dec-11 1:21am    
I was looking some PHP Built in function for this purpose. But now It looks, I will have to write a function to perform that function.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900