PHP preg匹配模式[var1] var2

mrm*_*mow -1 php preg-match-all preg-match

我正在尝试使用preg_match,但我无法获得正确的模式.

字符串看起来像[abc] def [ghi] jul [mno]pqr.

我需要类似的东西array(abc => def, ghi => jul, mno => pqr).

有任何想法吗?

ven*_*uil 5

试试这个正则表达式

/\[([a-z]+)\]( [a-z]+)?/
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

你可以添加isset(),$matches[2][$index]但我认为我的代码也有效.

@MateiMihai建议$result = array_combine($matches[1], $matches[2]);

  • 我会使用`$ result = array_combine($ matches [1],$ matches [2]);`而不是那个foreach (2认同)