如何分解符号串"-“中的偶数词?例如:
$string = 'tshirt-blue-124-tshirt-blue-124-tshirt-blue-124';或
$string = '333-red-333-red-333-red-333-red';我需要这样的数组:
$string[0] = 'tshirt-blue-124';
$string[1] = 'tshirt-blue-124';
$string[2] = 'tshirt-blue-124';或
$string[0] = '333-red';
$string[1] = '333-red';
$string[2] = '333-red';
$string[3] = '333-red';谢谢
发布于 2015-05-04 18:26:08
如果它总是每三个元素:
$string = 'tshirt-blue-124-tshirt-blue-124-tshirt-blue-124';
$newArray = array_chunk(explode('-', $string), 3);
array_walk(
$newArray,
function(&$value) {
$value = implode('-', $value);
});
var_dump($newArray);编辑
但是你必须提前知道有多少元素:
$splitValue = 2;
$string = '333-red-333-red-333-red-333-red';
$newArray = array_chunk(explode('-', $string), $splitValue);
array_walk(
$newArray,
function(&$value) {
$value = implode('-', $value);
});
var_dump($newArray);编辑#2
如果您不知道在重复块中有多少元素,那么可以查看Lempel-Ziv-Welsh (LZW) compression algorithm。它建立在检测字符串中的重复并利用它们进行压缩的基础上。您可以使用Suffix Trie数据结构来简化逻辑。
编辑#3
作为尝试确定拆分大小的一种简单方法:
function getSplitSize($string) {
$splitSize = 2;
do {
$tempArray = array_chunk(explode('-', $string), $splitSize);
if ($tempArray[0] == $tempArray[1])
return $splitSize;
++$splitSize;
} while ($splitSize <= count($tempArray));
throw new Exception('No repetition found');
}
function splitStringOnRepetition($string) {
$newArray = array_chunk(explode('-', $string), getSplitSize($string));
array_walk(
$newArray,
function(&$value) {
$value = implode('-', $value);
}
);
return $newArray;
}
$string = 'tshirt-blue-124-tshirt-blue-124-tshirt-blue-124';
$array = splitStringOnRepetition($string);
var_dump($array);
$string = '333-red-333-red-333-red-333-red';
$array = splitStringOnRepetition($string);
var_dump($array);发布于 2015-05-04 18:39:44
对于更高级但更有效的方法,您可以使用正则表达式匹配,使用preg_match()
$string = 'tshirt-blue-124-tshirt-blue-125-tshirt-blue-126';
$pattern = "/([A-Za-z]*-[A-Za-z]*-[\d]*)-?/";
preg_match_all($pattern, $string, $matches);
echo "<pre>";
print_r($matches[1]);
echo "</pre>";它将输出:
Array
(
[0] => tshirt-blue-124
[1] => tshirt-blue-125
[2] => tshirt-blue-126
)您可以按您想要的方式设置图案。
发布于 2015-05-04 18:24:45
你可以这样做
$string = 'tshirt-blue-124-tshirt-blue-124-tshirt-blue-124';
$tmp = explode("-", $string);
while ($tmp) {
$output[] = implode('-', array_splice($tmp, 0, 3));
}
print_r($output);https://stackoverflow.com/questions/30027691
复制相似问题