This question already has answers here:
How to get the shortest rather than longest possible regex match with preg_match()

(3个答案)


1年前关闭。




我有一个字符串(来自文件):
ILX (New for 2013!)

Overview: The least expensive route to Honda's premium-label goodness

Drivetrain: Two four-cylinder engines to choose from as well as a gas-electric hybrid; front-wheel-drive only.

我如何获得字符串:
$writeup = file_get_contents($car_files_path . $manufacture . '/Stories/'.$story);

我要匹配概述行(Overview: The least expensive route to Honda's premium-label goodness)。实现此目的的最佳方法是什么。

我尝试了。*\n,但这将匹配所有内容,然后匹配新行。有没有办法使正则表达式不贪心?

我试过了:preg_match('/^Overview:\s.*$/im', $writeup, $overall_matches)我没有任何匹配

最佳答案

在量词后添加?,使其变得不太贪婪。在这种情况下,您的正则表达式将为.*?\n

要专门匹配以“Overview:”开头的行,请使用以下正则表达式:

/^Overview:\s.*$/im
m修饰符允许^$匹配行的开头和结尾,而不是整个搜索字符串。请注意,除非.不匹配换行符,否则除非您使用s修饰符,否则无需使其变得不愉快-实际上,在此处使其不愉快将不利于性能。

关于php - PHP的preg_match非贪婪? [复制],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14967485/

10-14 15:25
查看更多