Regex,只匹配最后一个结果


Regex, match only the last one result

尝试过这个,但没有成功。匹配两个结果(请参见示例)。

$lines = preg_grep("/1'.11'.'s'w*/m", $lines);

示例

1.11 Test
1.11 Test //other paragraph

只需要找到这个:

1.11 Test //other paragraph

您可以改用preg_match()。或者,preg_match可以在数组中存储匹配的字符序列,然后可以拾取该数组的最后一个元素。

$result = null;
$matches = array();
$pattern = '/1'.11.+/';
$string = "1.11 Test
  asd 123
  1.11 Test //other paragraph
  asda";
$tmp = preg_match($pattern, $string, $matches);
if ($tmp === 1) $result = end($matches);
unset($matches, $pattern, $string, $tmp);
var_dump($result);

您的regexp模式也将失败,因为第二个点(''.)永远不会匹配。

由于您的输入$lines是一个数组,并且您似乎希望获得以1.11开头并包含一个单词和一个注释的项,因此可以使用

$lines = preg_grep('~^1'.11's*'w+'s*//~', $lines);

查看IDEONE演示

解释:

  • ^-字符串的开头
  • 1'.11-文字1.11
  • 's*-零个或多个空白符号
  • 'w+-1个或多个字([a-zA-Z0-9_])符号
  • 's*//-后面跟着文字字符序列//的零个或多个空白符号