php explode()函数问题 - 空格
我希望将文本字符串拆分为空格分隔的单词。 我用php explode()函数问题 - 空格
$words=explode(" ", $text);
不幸的是,这种方法并不能很好地为我工作,因为我想知道有多少空间之间都英寸
有没有什么更好的方法来做到这一点不是通过整个$文字,符号的符号去,用while
语句来填写$用整数位($spaces=array();
)(空格数量,在大多数情况下,1)和用符号将文本读入$ words = array()符号?
这里是一个额外的解释。
$text="Hello_world_____123"; //symbol "_" actually means a space
需要:
$words=("Hello","world","123");
$spaces=(1,5);
有很多方法可以做到你想要做什么,但我可能会选择preg_split()和array_map()组合:
$text = 'Hello world 123';
$words = preg_split('/\s+/', $text, NULL, PREG_SPLIT_NO_EMPTY);
$spaces = array_map(function ($sp) {
return strlen($sp);
}, preg_split('/\S+/', $text, NULL, PREG_SPLIT_NO_EMPTY));
var_dump($words, $spaces);
输出:
array(3) {
[0]=>
string(5) "Hello"
[1]=>
string(5) "world"
[2]=>
string(3) "123"
}
array(2) {
[0]=>
int(1)
[1]=>
int(5)
}
这是优雅,紧凑,我相信它速度快(比我猜想的更快)。有用。谢谢。 – Haradzieniec 2012-04-17 18:44:41
使用正则表达式来代替:
$words = preg_split('/\s+/', $text)
编辑
$spaces = array();
$results = preg_split('/[^\s]+/', $text);
foreach ($results as $result) {
if (strlen($result) > 0) {
$spaces [] = strlen($result);
}
}
他只需要空间的数量。 – Ozzy 2012-04-17 18:24:20
这是如何回答OP的问题? – webbiedave 2012-04-17 18:26:05
我被'我希望将文本字符串拆分为空格分隔的单词' – Tchoupi 2012-04-17 18:26:42
你仍然可以得到的空格数我n between like:
$words = explode(" ", $text);
$spaces = sizeof($words)-1;
这不适合你吗?
谢谢,但并不是说每对单词之间有多少空格甚至没有说空间的总数。 – Haradzieniec 2012-04-17 18:24:42
@Haradzieniec我以为你想分离每个单词?什么词有他们的空间? :/空格的数量是$ spaces'(数组中的字数 - 1)' – Ozzy 2012-04-17 18:26:35
我给一个问题解释了一个例子。谢谢。 – Haradzieniec 2012-04-17 18:28:50
正则表达式是你的朋友。 :) – 2012-04-17 18:22:09
嗯... substr_count会给我6上面的例子。 preg_split分割(任意数量)将字符串分成3个字。我如何知道6 = 5 + 1,但不是3 + 3? – Haradzieniec 2012-04-17 18:34:50