0

preg_match で名前付きサブパターンを使用して、配列内の行に名前を付けることができることを知っています: (?P<sval1>[\w-]+). これに関する問題は、「sval1」が事前定義されていることです。この名前付きサブパターンを正規表現ルックアップ自体の一部として作成することは可能ですか?

たとえば、テキスト フィールドが次のような場合:

step=5
min=0
max=100

基本的に、preg_match を使用して配列を作成したいと思います。

{
    [step] => 5
    [min] => 0
    [max] => 100
}

ユーザーは、テキスト エントリに好きなだけフィールドを追加できます。そのため、入力に基づいて配列エントリを動的に生成する必要があります。これを行う簡単な方法はありますか?

4

1 に答える 1

1
$str = 'step=5
min=0
max=100';

$output = array();
$array = explode("\n",$str);
foreach($array as $a){
    $output[substr($a,0,strpos($a,"="))] = substr($a,strpos($a,"=")+1);
}

echo '<pre>';
print_r($output);
echo '</pre>';

また:

$str = 'step=5
min=0
max=100';

$output = array();
preg_match_all("/(.*)=(.*)/",$str,$matches);
if(isset($matches[1]) && isset($matches[2])){
    foreach($matches[1] as $k=>$m){
        $output[$m] = $matches[2][$k];
    }
}


echo '<pre>';
print_r($output);
echo '</pre>';

またはコメントに基づいて:

$str = 'step=5
min=0
max=100';

$output = array();
preg_match_all("/(.*)=(.*)/",$str,$matches);
if(isset($matches[1],$matches[2])){
    $output = array_combine($matches[1],$matches[2]);
}


echo '<pre>';
print_r($output);
echo '</pre>';
于 2013-01-05T18:10:49.303 に答える