PHP 爆炸:通过使用空格分隔符将字符串拆分为单词


php explode: split string into words by using space a delimiter

$str = "This is a    string";
$words = explode(" ", $str);

工作正常,但空格仍然进入数组:

$words === array ('This', 'is', 'a', '', '', '', 'string');//true

我宁愿只有没有空格的单词,并将有关空格数的信息分开。

$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true

刚刚添加:(1, 1, 4)表示第一个单词后一个空格,第二个单词后一个空格,第三个单词后 4 个空格。

有什么办法可以快速完成吗?

谢谢。

要将字符串拆分为数组,应使用 preg_split:

$string = 'This is a    string';
$data   = preg_split('/'s+/', $string);

您的第二部分(计算空格):

$string = 'This is a    string';
preg_match_all('/'s+/', $string, $matches);
$result = array_map('strlen', $matches[0]);// [1, 1, 4]

这是一种方法,拆分字符串并运行一次正则表达式,然后解析结果以查看哪些段被捕获为拆分(因此只有空格),或者哪些是单词:

$temp = preg_split('/('s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
    if( strlen( trim( $item)) === 0) {
        $spaces[] = strlen( $item);
    } else {
        $result[] = $item;
    }
    return $result;
}, array());

从这个演示中可以看到,$words是:

Array
(
    [0] => This
    [1] => is
    [2] => a
    [3] => string
)

$spaces是:

Array
(
    [0] => 1
    [1] => 1
    [2] => 4
)

您可以将preg_split()用于第一个数组:

$str   = 'This is a    string';
$words = preg_split('#'s+#', $str);

preg_match_all() 对于$spaces数组:

preg_match_all('#'s+#', $str, $m);
$spaces = array_map('strlen', $m[0]);

另一种方法是使用 foreach 循环。

$str = "This is a    string";
$words = explode(" ", $str);
$spaces=array();
$others=array();
foreach($words as $word)
{
if($word==' ')
{
array_push($spaces,$word);
}
else
{
array_push($others,$word);
}
}

以下是性能测试的结果:

$str = "This is a    string";
var_dump(time());
for ($i=1;$i<100000;$i++){
//Alma Do Mundo  - the winner
$rgData = preg_split('/'s+/', $str);

preg_match_all('/'s+/', $str, $rgMatches);
$rgResult = array_map('strlen', $rgMatches[0]);// [1,1,4]

}
print_r($rgData); print_r( $rgResult);
var_dump(time());


for ($i=1;$i<100000;$i++){
//nickb
$temp = preg_split('/('s+)/', $str, -1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
    if( strlen( trim( $item)) === 0) {
        $spaces[] = strlen( $item);
    } else {
        $result[] = $item;
    }
    return $result;
}, array());
}

print_r( $words); print_r( $spaces);
var_dump(time());

国际(1378392870)数组( [0] => 这个 [1] => 是 [2] => a [3] =>字符串)数组( [0] => 1 [1] => 1 [2] => 4)国际(1378392871)数组( [0] => 这个 [1] => 是 [2] => a [3] =>字符串)数组( [0] => 1 [1] => 1 [2] => 4)国际(1378392873)

$financialYear = 2015-2016;

$test = explode('-',$financialYear);
echo $test[0]; // 2015
echo $test[1]; // 2016

前面的答案已经很好地证明了使用正则表达式进行拆分,但我认为这是调用ctype_space()以确定哪个结果数组应该接收遇到的值的完美案例。

代码:(演示)

$string = "This is a    string";
$words = [];
$spaces = [];
foreach (preg_split('~( +)~', $string, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $s) {
    if (ctype_space($s)) {
        $spaces[] = strlen($s);
    } else {
        $words[] = $s;
    }
}
var_export([
    'words' => $words,
    'spaces' => $spaces
]);

输出:

array (
  'words' => 
  array (
    0 => 'This',
    1 => 'is',
    2 => 'a',
    3 => 'string',
  ),
  'spaces' => 
  array (
    0 => 1,
    1 => 1,
    2 => 4,
  ),
)

如果要替换preg_split()使用的管道常量,则可以只使用3(Demo)。 这表示PREG_SPLIT_NO_EMPTY 1加上PREG_SPLIT_DELIM_CAPTURE 2。 请注意,随着代码宽度的减小,您也会失去代码的可读性。

preg_split('~( +)~', $string, -1, 3)

这个呢?有人愿意对此进行剖析吗?

    $str = str_replace(["'t", "'r", "'r", "'0", "'v"], ' ', $str); // 'v -> vertical space, see trim()
    $words = explode(' ', $str);
    $words = array_filter($words); // there would be lots elements from lots of spaces so skip them.