PHP explode 函数接受超过 1 个空格,PHP,EXPLODE,WHITESPACES
PHP explode function takes in more than 1 whitespace, PHP, EXPLODE, WHITESPACES
我有一个包含几个单词的数组,我试图仅在 一个 空格处展开它,但由于某种原因展开时它也会计算空格.我该如何阻止它?
<?php
$string = "I'm just so peachy, right now";
$string = explode(" ", $string);
$count = count($string);
$tempCount = 0;
while ($tempCount < $count) {
echo $string[$tempCount]."$tempCount<br>";
$tempCount++;
}
?>
实际输出:
I'm0
just1
2
3
4
5
6
7
8
9
10
11
12
so13
peachy,14
right15
now16
预期输出:
I'm0
just1
so2
peachy,3
right4
now5
使用 preg_split、http://php.net/manual/en/function.preg-split.php,这将使用正则表达式,因此您可以告诉它把所有连续的空格保持为一个。
$string = 'I\'m just so peachy, right now';
$spaced = preg_split('~\h+~', $string);
print_r($spaced);
输出:
Array
(
[0] => I'm
[1] => just
[2] => so
[3] => peachy,
[4] => right
[5] => now
)
PHP 演示:http://3v4l.org/a5cg5
正则表达式演示:https://regex101.com/r/vO1qU0/1
我有一个包含几个单词的数组,我试图仅在 一个 空格处展开它,但由于某种原因展开时它也会计算空格.我该如何阻止它?
<?php
$string = "I'm just so peachy, right now";
$string = explode(" ", $string);
$count = count($string);
$tempCount = 0;
while ($tempCount < $count) {
echo $string[$tempCount]."$tempCount<br>";
$tempCount++;
}
?>
实际输出:
I'm0
just1
2
3
4
5
6
7
8
9
10
11
12
so13
peachy,14
right15
now16
预期输出:
I'm0
just1
so2
peachy,3
right4
now5
使用 preg_split、http://php.net/manual/en/function.preg-split.php,这将使用正则表达式,因此您可以告诉它把所有连续的空格保持为一个。
$string = 'I\'m just so peachy, right now';
$spaced = preg_split('~\h+~', $string);
print_r($spaced);
输出:
Array
(
[0] => I'm
[1] => just
[2] => so
[3] => peachy,
[4] => right
[5] => now
)
PHP 演示:http://3v4l.org/a5cg5
正则表达式演示:https://regex101.com/r/vO1qU0/1