1

我在文本文件中有以下记录,需要从文本文件中提取该记录并将它们视为单独的数组变量

r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)用管道(|)分隔

我需要将其表示为数组单独使用,如下所示

$r1= Array
(
[0] => 1
[1] => 2
[2] => 3
)

$r2=Array
(
[0] => 4
[1] => 5
[2] => 6
)

我不知道该怎么做,在php中可以吗?

4

6 回答 6

1

只是一个简单的正则表达式来分解字符串,然后对每个组进行分解:

if (preg_match_all('#(\w+)=\(([\d,]*)\)#', $s, $matches)) {
    foreach ($matches[2] as $i => $groups) {
        $group_name = $matches[1][$i];
        $$group_name = array_map('intval', explode(',', $groups));
    }
}

print_r($r1);
print_r($r3);
print_r($rn);
于 2012-05-21T07:06:17.927 回答
0
$data = "r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";

$arr = explode("|", $data);

$finArray = array();

foreach($arr as $key=>$value)
{
    $single = explode('(', $value);
    $finArray[] = explode(',', str_replace(')', '', $single[1]));
}

print_r($finArray);
于 2012-05-21T07:01:29.947 回答
0

您可以使用评估

//Assuming  you can pull the content from text file using fread

$temp = "r1=(1,2,3)|r2=(4,5,6)";
$temp=str_replace("=","=array",$temp);
$split=explode("|",$temp);
echo "<pre>";
foreach($split as $k=>$v){
      $v="$".$v.";";
      //Evaluate a string as PHP code .i.e You will get r1,r2 as a variable now which is array
      eval($v);
}

print_r($r1);
print_r($r2);
于 2012-05-21T07:02:10.117 回答
0

此代码将帮助您:-

  <?php
    $file = "/tmp/file1.txt"; // this is your file path
    $f = fopen($file, "r");
    while ( $line = fgets($f, 1000) ) {
    print $line;

    $a=explode('|',$line);
    print_r($a);  // I have explode based on | for you...

foreach($a as $key=>$value)
{
    print_r($value);
}

fclose($文件); } ?>

““或者””

$a="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";

$a=explode('|',$a);
print_r($a);
于 2012-05-21T07:03:16.060 回答
0

可以这样做:

$string="r1=(1,2,3)|r2=(4,5,6)|r3=(1,2,3,4,5,7)|rn=(9,6,7,8)";
$string=str_repla("r1=","",$string);
$yourArray=explode('|', $string);
于 2012-05-21T07:03:39.710 回答
0
    <?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
$str = $line;
}
$str1 = explode("|",$str);
foreach($str1 as $temp) {
    $str2 = explode("=",$temp);
    $data[$str2[0]] = explode(",",trim($str2[1],"()"));
}
echo '<pre>';
print_r($data);
echo '</pre>';
?>

这将完成你的工作。

于 2012-05-21T07:34:19.853 回答