PHP我需要将逗号分隔的字符串拆分成一个数组,但是当逗号出现在数字之间时,请忽略它

问题描述 投票:2回答:3

我有一个字符串发送到php,我需要将其转换为数组。在大多数情况下,因为在正确的plac3es中用逗号分隔字符串,所以没有问题。但是有时我需要忽略两个数字之间的逗号。我尝试过preg_split,但要向后看,但要向前看,但我总是会丢失字符串的最后一个或开头的字母之一。

我已经为此苦苦挣扎了好几天。我不能使用explode,否则数组包含以1,2逗号分隔的子字符串。

例如:

bears, tigers, lions, sword-1,2-fish, penguins

我需要PHP来忽略剑1,2,-fish中的逗号并返回:

[0] ==> bears
[1] ==> tigers
[2] ==> lions
[3] ==> sword-1,2-fish
[4] ==> penguins

请任何人帮忙吗?

php arrays
3个回答
1
投票

使用negative lookbehind and negative lookahead的完美案例:

$string = 'bears, tigers, lions, sword-1,2-fish, penguins';
$result = preg_split('#(?<!\d),(?!\d)#', $string);

0
投票

您还需要与,和空格一起爆炸。

<?php

$string = 'bears, tigers, lions, sword-1,2-fish, penguins';
$explodedArray = explode(', ',$string);
print_r($explodedArray);

输出:https://3v4l.org/louoo

您可以通过空间爆炸,然后从所有元素中移除,

<?php

$string = 'bears, tigers, lions, sword-1,2-fish, penguins';
$explodedArray = explode(' ',$string);
array_walk($explodedArray, function(&$value, &$key) {
    $value = rtrim($value,',');
});

print_r($explodedArray);

输出:-https://3v4l.org/iD0ra


0
投票

感谢您的贡献-我终于按照上述建议使用了环顾方法进行了整理。

$pattern = "/(?<=\D),(?=\D)/";                  // the expression only accepts commas that are NOT preceded by or followed by a digit (\D is NOT a digit)
$arr = preg_split($pattern, $data8);


$wrongArray="";
foreach ($arr as $wrong){
$wrongArray.="<li style='font-family:Verdana;font-size:12px;color:maroon'>".$wrong."</li>";
}

我还将研究其他建议,以了解它们为什么起作用。非常感谢。

© www.soinside.com 2019 - 2024. All rights reserved.