PHP preg 匹配模式 [var1] var2
PHP preg match pattern [var1] var2
我正在尝试开始使用 preg_match,但找不到正确的模式。
字符串看起来像 [abc] def [ghi] jul [mno]
pqr.
我需要 array(abc => def, ghi => jul, mno => pqr)
.
有什么想法吗?
试试这个正则表达式
/\[([a-z]+)\]( [a-z]+)?/
在preg_match_all()
之后试试
$regex = '/\[([a-z]+)\][ ]?([a-z]+)?/';
$string = '[abc] def [ghi] jul [mno] pqr';
preg_match_all($regex, $string, $matches);
$arr = array();
foreach($matches[1] as $index => $match){
$arr[$match] = $matches[2][$index];
}
print_r($arr);
您可以为 $matches[2][$index]
添加 isset()
,但我认为我的代码也可以。
@MateiMihai建议$result = array_combine($matches[1], $matches[2]);
我正在尝试开始使用 preg_match,但找不到正确的模式。
字符串看起来像 [abc] def [ghi] jul [mno]
pqr.
我需要 array(abc => def, ghi => jul, mno => pqr)
.
有什么想法吗?
试试这个正则表达式
/\[([a-z]+)\]( [a-z]+)?/
在preg_match_all()
之后试试
$regex = '/\[([a-z]+)\][ ]?([a-z]+)?/';
$string = '[abc] def [ghi] jul [mno] pqr';
preg_match_all($regex, $string, $matches);
$arr = array();
foreach($matches[1] as $index => $match){
$arr[$match] = $matches[2][$index];
}
print_r($arr);
您可以为 $matches[2][$index]
添加 isset()
,但我认为我的代码也可以。
@MateiMihai建议$result = array_combine($matches[1], $matches[2]);