PHP 在分隔符的第二个实例上爆炸

问题描述 投票:0回答:5

我正在尝试使用 PHP 分解字符串,但只有在分解之前检测到分隔符的第二个实例时,对于我的情况,我想在检测到第二个空格后分解它。

我的绳子

Apple Green Yellow Four Seven Gray

我的欲望输出

Apple Green
Yellow Four
Seven Gray

我的初始代码

$string = 'Apple Green Yellow Four Seven Gray';
$new = explode(' ',$string);

如何使用 PHP 的爆炸或任何分离方法来实现这一点?预先感谢!

php explode
5个回答
5
投票

好问题——可以通过多种方式完成。我想出了这个 1 -

 $data='Apple Green Yellow Blue';


$split = array_map(
    function($value) {
        return implode(' ', $value);
    },
    array_chunk(explode(' ', $data), 2)
);

var_dump($split);

2
投票

您也可以使用这个:

$string = 'Apple Green Yellow Four Seven Gray';
$lastPos = 0;
$flag = 0;
while (($lastPos = strpos($string, " ", $lastPos))!== false) {  
    if(($flag%2) == 1)
    {
        $string[$lastPos] = "@";
    }
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen(" ");
    $flag++;
}
$new = explode('@',$string);
print_r($new);
exit;

1
投票

您可以使用正则表达式。

$founds = array();
$text='Apple Green Yellow Four Seven Gray';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $text, $founds);

也可参考以下答案


1
投票

使用

explode
您无法获得所需的输出。您必须使用
preg_match_all
才能找到所有值。 这是一个例子:

$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
       'Apple Green Yellow Four Seven Gray',$matches);

print_r($matches);

如果您有任何问题,请告诉我。


0
投票

这正是

preg_split()
的任务类型。

匹配每两组非空白字符后跟一个空格。使用

\K
在第二个空格之前重置全字符串匹配 - 这将确保在拆分时消耗第二个空格。

代码:(演示

$string = 'Apple Green Yellow Four Seven Gray';

var_export(
    preg_split('/(?:\S*\K ){2}/', $string)
);
© www.soinside.com 2019 - 2024. All rights reserved.