如何从字符串中提取单词 [英] How to extract words from a string

查看:110
本文介绍了如何从字符串中提取单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串中提取单词.
例如,如果字符串是

$str = "It is a hot day";



我想把这个字符串中的五个词作为数组

$word[0] = ''It'';
$word[1] = ''is'';
$word[2] = ''a'';
$word[3] = ''hot'';
$word[4] = ''day'';


我已经使用爆炸功能实现了这样的目的

$str = "It is a hot day";
$word = explode(" ",str);



直到单词之间或之后的空格数为1为止,它都可以正常工作.但是,如果任何单词之间或之后的空格数或多个,它将​​作为单词获得该空格.
例如,如果字符串是

$str = "It is  a hot day";


现在,它在"is"和"a"之间有两个空格.因此,当我使用explode函数将其转换为数组时,它将给我六个元素,而不是五个.
因此,我只希望数组中的单词值不希望任何空格作为数组值.我该怎么做?

解决方案

str =今天很热";



我想将这个字符串中的五个单词作为数组

 


word [0] =``它'';


word [1] =``is'';

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?

解决方案

str = "It is a hot day";



I want to get the five words in this string as array


word[0] = ''It'';


word[1] = ''is'';


这篇关于如何从字符串中提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆