简体   繁体   中英

Php How to split a string containing special characters

Hello I have a string as

$str = "[10-1],[20-2],[30-3],";

this I want to split int two arrays as-

Array1
(
   [0] => 10
   [1] => 20
   [2] => 30
)

Array2
(
   [0] => 1
   [1] => 2
   [2] => 3
)

How it can be done? also my variable $str is varying depending upon values..

Thanks..

Split it using regex:

$str = "[10-1],[20-2],[30-3],";

$matches = array();
preg_match_all('/\[(\d+)-(\d+)\],/', $str, $matches);

If you unset($matches[0]); the remaining is exactly what you asked for.

I would use explode() . Theres almost certainly a better way, but its never let me down.

$array1 = [];
$array2 = [];
$str = "[10-1],[20-2],[30-3]";
$split = explode ('[', $str);
foreach ($split as $item) {
    $array = explode (']', $item);
    $array = explode('-', $array[0]);
    $array1[] = $array[1];
    $array2[] = $array[0];
}

Does this work for you?

$str = "[10-1],[20-2],[30-3],";

$str = str_replace(array("[","]"),"",$str);

$parts = explode(",",$str);

$arr1 = [];
$arr2 = [];
foreach($parts as $part){
    if($part){
        $arr_parts = explode("-",$part);
        $arr1[] = $arr_parts[0];
        $arr2[] = $arr_parts[1];
    }
}

echo "<pre>";
var_dump($arr1,$arr2);

Output is:

array(3) {
    [0]=>
    string(2) "10"
    [1]=>
    string(2) "20"
    [2]=>
    string(2) "30"
}
array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
}

Based on:

$str = "[10-1],[10-1],[30-3],";

$val = explode(",",$str); //Now we got an array similar to:Array ( [0] => [10-1] [1] => [10-1] [2] => [30-3])
$exitArray1 = array();
$exitArray2 = array();

for ($i = 0; $i < count ($val); $i++){
 if(strlen($val[$i]) >0){
  $val[$i] = substr($val[$i],0,-1); //got [10-1
  $val[$i] = substr($val[$i],1); // got 10-1
  $temp = explode("-",);// Split on -
  $exitArray1[] = $temp[0]; //put 10 in first array
  $exitArray2[] = $temp[1]; //put 1 in second array
 }
}

Another possible solution. But usng regex is the best bet:

<?php
$str = "[10-1],[20-2],[30-3]";
$arr = explode(',',$str);
$array1 = array();
$array2 = array();
foreach($arr as $val) {
    $val = trim($val,'[]');
    $temp = explode('-', $val);
    $array1[] = $temp[0];
    $array2[] = $temp[1];
}
echo '<pre>';
print_r($array1);
print_r($array2);
?>

Output:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM