Php 正则表达式的动态命名子模式?
我知道我可以使用preg_match中的命名子模式来命名数组中的行:Php 正则表达式的动态命名子模式?,php,preg-match,Php,Preg Match,我知道我可以使用preg_match中的命名子模式来命名数组中的行:(?p[\w-]+)。我的问题是“sval1”是预定义的。是否可以将此命名子模式作为正则表达式查找本身的一部分 例如,如果文本字段如下所示: step=5 min=0 max=100 我想使用preg_匹配创建一个基本上具有以下内容的数组: { [step] => 5 [min] => 0 [max] => 100 } 用户可以在文本条目中添加任意多的字段;因此,它需要根据输入动态生
(?p[\w-]+)
。我的问题是“sval1”是预定义的。是否可以将此命名子模式作为正则表达式查找本身的一部分
例如,如果文本字段如下所示:
step=5
min=0
max=100
我想使用preg_匹配创建一个基本上具有以下内容的数组:
{
[step] => 5
[min] => 0
[max] => 100
}
用户可以在文本条目中添加任意多的字段;因此,它需要根据输入动态生成数组项。有没有一种简单的方法可以做到这一点?$str='step=5
$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>';
最小值=0
最大值=100';
$output=array();
$array=explode(“\n”,$str);
foreach($a数组){
$output[substr($a,0,strpos($a,“=”))=substr($a,strpos($a,“=”))+1);
}
回声';
打印(输出);
回声';
或:
$str='step=5
最小值=0
最大值=100';
$output=array();
preg_match_all(“/(.*)=(.*)/”,$str,$matches);
if(isset($matches[1])&isset($matches[2])){
foreach($k=>m,与[1]匹配){
$output[$m]=$matches[2][$k];
}
}
回声';
打印(输出);
回声';
或根据评论:
$str='step=5
最小值=0
最大值=100';
$output=array();
preg_match_all(“/(.*)=(.*)/”,$str,$matches);
if(isset($matches[1],$matches[2])){
$output=array_combine($matches[1],$matches[2]);
}
回声';
打印(输出);
回声';
很有趣,但不是。它需要类似于PCRE不允许的(?P..)
的东西。但只需在此处使用array\u combine
而不是preg\u match\u all
;这通常是关联对匹配的一种方便方法。哦!我不知道我怎么会错过。可以使用$output=array\u combine($matches[1],$matches[2])代码>而不是循环,否则+1第二个半示例似乎是最好的方法。与其执行if(isset($\u foo)和&isset($\u bar))
您只需执行:if(isset($\u foo,$\u bar…)
注释的组合将导致第三个更有效的答案
$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>';