Php如何拆分包含特殊字符的字符串

时间:2014-12-12 10:59:49

标签: php

您好我有一个字符串

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

这我想把两个数组拆分为 -

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

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

怎么做?我的变量 $ str 也会根据值而变化。

谢谢..

5 个答案:

答案 0 :(得分:6)

使用正则表达式将其拆分:

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

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

如果您unset($matches[0]);剩下的就是您要求的内容。

答案 1 :(得分:0)

我会使用explode()。几乎可以肯定这是一种更好的方式,但它永远不会让我失望。

$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];
}

答案 2 :(得分:0)

这对你有用吗?

$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);

输出是:

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"
}

答案 3 :(得分:0)

基于:

$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
 }
}

答案 4 :(得分:0)

另一种可能的解决方案。但使用正则表达式是最好的选择:

<?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);
?>

输出:

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