PHP在分隔符的第二个实例上爆炸
我试图使用PHP分解字符串,但仅当在分解前检测到分隔符的第二个实例时,我想在检测到第二个空格后分解它 我的绳子PHP在分隔符的第二个实例上爆炸,php,explode,Php,Explode,我试图使用PHP分解字符串,但仅当在分解前检测到分隔符的第二个实例时,我想在检测到第二个空格后分解它 我的绳子 苹果绿黄四七灰 我的欲望输出 Apple Green Yellow Four Seven Gray 我的初始代码 $string = 'Apple Green Yellow Four Seven Gray'; $new = explode(' ',$string); 如何使用explode或PHP中的任何分离方法来实现这一点?提前谢谢 您可以使用正则表达式来实现这一点 $found
苹果绿黄四七灰
我的欲望输出
Apple Green
Yellow Four
Seven Gray
我的初始代码
$string = 'Apple Green Yellow Four Seven Gray';
$new = explode(' ',$string);
如何使用explode或PHP中的任何分离方法来实现这一点?提前谢谢 您可以使用正则表达式来实现这一点
$founds = array();
$text='Apple Green Yellow Four Seven Gray';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $text, $founds);
也请参考以下内容您可以使用正则表达式来实现这一点
$founds = array();
$text='Apple Green Yellow Four Seven Gray';
preg_match('/^([^ ]+ +[^ ]+) +(.*)$/', $text, $founds);
使用
分解
也可以参考以下内容,您无法获得所需的输出。您必须使用preg\u match\u all
查找所有值。
以下是一个例子:
$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
'Apple Green Yellow Four Seven Gray',$matches);
print_r($matches);
如果您有任何问题,请告诉我。使用
分解
无法获得所需的输出。您必须使用preg\u match\u all
查找所有值。
以下是一个例子:
$matches = array();
preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
'Apple Green Yellow Four Seven Gray',$matches);
print_r($matches);
如果您有任何问题,请告诉我。问得好-可以通过多种方式解决。我想出了这个1-
$data='Apple Green Yellow Blue';
$split = array_map(
function($value) {
return implode(' ', $value);
},
array_chunk(explode(' ', $data), 2)
);
var_dump($split);
好问题-可以用很多方法来完成。我想出了这个1-
$data='Apple Green Yellow Blue';
$split = array_map(
function($value) {
return implode(' ', $value);
},
array_chunk(explode(' ', $data), 2)
);
var_dump($split);
您也可以使用此选项:
$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;
您也可以使用此选项:
$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;
我的输出是
数组([0]=>苹果绿黄四七灰[1]=>苹果绿[2]=>黄四七灰)
它错过了我在答案中引用的链接上的七灰
。它将帮助您查看我的输出是数组([0]=>苹果绿黄四七灰[1]=>苹果绿[2]=>黄四七灰)
它错过了我在答案中引用的链接上的七灰
。在我的情况下,它只返回了数组([0]=>苹果绿[1]=>黄四七灰)
不知怎么的,它错过了七灰
好的@KaoriYui..我做错了,请看我更新的答案。.它会工作得很好的,所以我把分隔符改为空格,把变量转储改为打印,这是最简单的,谢谢哦,再次…抱歉,伙计..我将它更新为空格分隔符。在我的例子中,它只返回数组([0]=>苹果绿[1]=>黄色四七灰色)
不知何故它错过了Seven Gray
ok@KaoriYui..我做错了,请查看我的更新答案..它会工作得很好好好的,所以我将分隔符改为空格,将变量转储改为打印,这是最简单的,谢谢!哦,再一次…对不起,伙计…我把它更新为空格分隔符。