在字符串

时间:2016-06-03 21:40:15

标签: php regex string

如何在字符串中获取所有匹配项? 例如,字符串是

hhh (12) 5cb (jkl) jj

brt (11) {

我想在第一个字符串中获取 12 jkl ,在第二个字符串中获取 11

我试过

preg_match("/.*\((.*)\).*/", $input_line, $output_array);

但这只是字符串中的最后一场比赛。

2 个答案:

答案 0 :(得分:2)

您正在寻找的RegEx应该是这样的:

preg_match_all("/\((.*?)\)/", $input_line, $output_array);

Live example.

说明:

  (.*)     #grab all characters
  (.*?)    #as little as possible
\((.*?)\)  #that are within brackets

您还需要使用preg_match_all代替preg_match,以便获得与该模式匹配的所有字符串。

答案 1 :(得分:0)

使用preg_match_all代替preg_match。它返回一个包含每个匹配信息的二维数组。

您还需要修复正则表达式。取出括号周围的.*,因为它使它与字符串中的其他内容匹配,因此只有一个匹配。在括号内你需要使用非贪婪的量词,所以它不会超出近括号。

$input_line = 'hhh (12) 5cb (jkl) jj';
preg_match_all("/.*\((.*?)\).*/", $input_line, $output_array);
print_r($output_array[1]); // array of all the capture group 1

DEMO

相关问题