PHP的preg_match非贪婪? [英] php preg_match non greedy?

查看:67
本文介绍了PHP的preg_match非贪婪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串(来自文件):

I have a string (from a file):

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).实现此目标的最佳方法是什么.

I want to match the overview line (Overview: The least expensive route to Honda's premium-label goodness). What is the best way to achieve this.

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

I tried .*\n, but that will match everything and then a new line. Is there a way to make regex non-greedy?

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

I have tried: preg_match('/^Overview:\s.*$/im', $writeup, $overall_matches) and I don't get any matches

推荐答案

在量词后添加?以使其不贪心.在这种情况下,您的正则表达式为.*?\n.

Add ? after the quantifier to make it ungreedy. In this case, your regex would be .*?\n.

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

To specifically match the line beginning with "Overview: ", use this regex:

/^Overview:\s.*$/im

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

The m modifier allows ^ and $ to match the start and end of lines instead of the entire search string. Note that there is no need to make it ungreedy since . does not match newlines unless you use the s modifier - in fact, making it ungreedy here would be bad for performance.

这篇关于PHP的preg_match非贪婪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆