字符串中用空格分隔的单词 [英] Separate space-delimited words in a string

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

问题描述

我有以下格式的文本字符串 $ str =" word1 word2 word3 word4"

i have a text string in the following format $str= "word1 word2 word3 word4 "

所以我想从字符串中分离出每个单词.两个单词之间用空格隔开 我怎么做.有内置功能可以做到这一点吗?

So i want to seperate each word from the string.Two words are seperated by a blank space How do i do that. IS there any built in function to do that?

推荐答案

最简单的方法是使用 explode :

The easiest would be to use explode:

$words = explode(' ', $str);

但这只接受固定的分隔符. split preg_split 确实接受正则表达式,以便您的单词可以用多个空格分隔:

But that does only accept fixed separators. split an preg_split do accept regular expressions so that your words can be separated by multiple spaces:

$words = split('\s+', $str);
// or
$words = preg_split('/\s+/', $str);

现在,您还可以使用 trim :

Now you can additionally remove leading and trailing spaces with trim:

$words = preg_split('/\s+/', trim($str));

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

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