phpexplode:使用空格作为分隔符将字符串拆分为单词 [英] php explode: split string into words by using space a delimiter
本文介绍了phpexplode:使用空格作为分隔符将字符串拆分为单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$str = "This is a string";
$words = explode(" ", $str);
工作正常,但空格仍然进入数组:
Works fine, but spaces still go into array:
$words === array ('This', 'is', 'a', '', '', '', 'string');//true
我更喜欢只有没有空格的单词,并且将有关空格数的信息分开.
I would prefer to have words only with no spaces and keep the information about the number of spaces separate.
$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true
刚刚补充:(1, 1, 4)
表示第一个词后一个空格,第二个词后一个空格,第三个词后4个空格.
Just added: (1, 1, 4)
means one space after the first word, one space after the second word and 4 spaces after the third word.
有什么办法可以快速完成吗?
Is there any way to do it fast?
谢谢.
推荐答案
要将 String 拆分为数组,应使用 preg_split:
For splitting the String into an array, you should use preg_split:
$string = 'This is a string';
$data = preg_split('/\s+/', $string);
你的第二部分(计算空格):
Your second part (counting spaces):
$string = 'This is a string';
preg_match_all('/\s+/', $string, $matches);
$result = array_map('strlen', $matches[0]);// [1, 1, 4]
这篇关于phpexplode:使用空格作为分隔符将字符串拆分为单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文