Tell me how to break the format string: 4044_90548_90791 to end up with: array (4044, 4044_9054, 4044_90548_90791);
|
6 answers
<?php $string = "4044_90548_90791"; // Вариант для строки с 3 элементами $result = preg_replace("/^(\d+)\_(\d+)\_(\d+)$/", "$1,$1_$2,$1_$2_$3", $string); $resultArray = explode(',', $result); print_r($resultArray); /** Array ( [0] => 4044 [1] => 4044_90548 [2] => 4044_90548_90791 ) **/ // Вариант для строки с любым количеством элементов $array = explode('_', $string); $resultArray = []; foreach ($array as $item) { $resultArray[] = empty($resultArray) ? $item : end($resultArray) . '_' . $item; } print_r($resultArray); /** Array ( [0] => 4044 [1] => 4044_90548 [2] => 4044_90548_90791 ) */ |
Everything turned out to be simple:
$categories = explode('_', '4044_90548_90791'); $explode = array(); $add = ''; $i = 0; while ($i <= count($categories)-1) { $explode[$i] = $add.$categories[$i]; $add .= $categories[$i].'_'; $i++; } |
Alternative option:
$s = '4044_90548_90791'; $l = strlen($s); $a = []; for ($i = 0; $i < $l; $i++) { if ($s[$i] === '_' || $i === $l - 1) { $a[] = substr($s, 0, $i); } } It is only necessary to note that it will not work with multibyte encodings (for this, it will be necessary to replace string functions with mb_ * analogs).
|
And one more option)
$path = '4044_90548_90791'; $path = explode('_', $path); for ($i = 1; $i < count($path); $i++) { $path[$i] = $path[$i-1] . '_' . path[$i]; } print_r($path); |
another variant with string functions:
$result = []; $pos = 0; while( ($pos = strpos($str, "_", $pos+1)) !== false){ $result[] = substr($str, 0, $pos); }; $result[] = $str; |
$res = explode("_", "4044_90548_90791"); $res[count($res) - 1] = "4044_90548_90791"; for($j = 1; $j < count($res) - 1; $j++) { $res[$j] = $res[0] ."_". $res[$j]; } print_r($res); |
$matches? :) - teran