PHP的爆炸:将字符串分割成字用空间分隔符 [英] php explode: split string into words by using space a delimiter

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

问题描述

  $海峡=这是一个字符串;
$字=爆炸(,$海峡);

工作正常,但仍有空间进入数组:

  $字===阵列('本','是','A','','','','串'); //真

我想preFER有只字不带空格和保存有关信息的的空格数分开的。

  $字===阵列('本','是','A','串'); //真
$空格===阵列(1,1,4-); //真

只是补充说:(1,1,4)表示首字一个空格,第二个字后的一个空间,第三个单词后,4个空格

有没有办法做到这一点快?

感谢您。


解决方案

有关拆分成字符串数组,你应该使用的 preg_split

  $字符串='这是一个字符串;
$数据= preg_split('/ \\ s + /',$字符串);

您第二部分(包括空格):

  $字符串='这是一个字符串;
preg_match_all('/ \\ s + /',$字符串,$匹配);
$结果= array_map('strlen的',$比赛[0]); // [1,1,4]

$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

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?

Thank you.

解决方案

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]

这篇关于PHP的爆炸:将字符串分割成字用空间分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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