PHP bir dize Patlayan

4 Cevap php

How do i explode this string '||25||34||73||94||116||128' i need to have a array like this

array (
 0 => '25',
 1 => '34',
 2 => '73',
 3 => '94',
 4 => '116',
 5 => '128'
)

, | ("|", $ dizi) patlayabilir benim için işe yaramadı ben bu diziyi olsun

array (
 0 => '',
 1 => '25',
 2 => '34',
 3 => '73',
 4 => '94',
 5 => '116',
 6 => '128',
) 

4 Cevap

Bir çözeltisi, özellikle if you can have empty values in the middle of the string, preg_split and its PREG_SPLIT_NO_EMPTY flag kullanmak olabilir:

$str = '||25||34||73||94||116||128';
$array = preg_split('/\|\|/', $str, -1, PREG_SPLIT_NO_EMPTY);
var_dump($array);

Size verecektir:

array
  0 => string '25' (length=2)
  1 => string '34' (length=2)
  2 => string '73' (length=2)
  3 => string '94' (length=2)
  4 => string '116' (length=3)
  5 => string '128' (length=3)


If you'll never have empty values in the middle of the string, though, using explode will be faster, even if you have to remove the || at the beginning and end of the string before calling it.

$str='||25||34||73||94||116||128';
$s = array_filter(explode("||",$str),is_numeric);
print_r($s);

çıktı

$ php test.php
Array
(
    [1] => 25
    [2] => 34
    [3] => 73
    [4] => 94
    [5] => 116
    [6] => 128
)

Sen yapabilirsin:

explode('||',substr($str,2));

Daha önce de belirttiğimiz çözümlerin yanı sıra, aynı zamanda daha sonra boş değerler filtre olabilir:

$arr = array_filter(explode("||", $str), function($val) { return trim($val) === ""; });

Bu örnek, PHP 5.3 veya daha büyük kullanarak, birini kullanarak değilseniz değiştirmek gerekir, bir anonymous function kullanan create_function :

$arr = array_filter(explode("||", $str), create_function('$val', 'return trim($val) === "";'));

Ya da önceden belirlenmiş bir işlevi ile:

function isEmptyString($str) {
    return trim($str) === "";
}
$arr = array_filter(explode("||", $str), "isEmptyString");