Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match non greedy? [duplicate]

Tags:

regex

php

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. 

How I get the string:

$writeup = file_get_contents($car_files_path . $manufacture . '/Stories/'.$story); 

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.

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

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

like image 228
Chris Muench Avatar asked Feb 19 '13 21:02

Chris Muench


People also ask

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What is non greedy regex?

A non-greedy match means that the regex engine matches as few characters as possible—so that it still can match the pattern in the given string.

What is Preg_match () function?

PHP preg_match() function. The preg_match() function is a built-in function of PHP that performs a regular expression match. This function searches the string for pattern, and returns true if the pattern exists otherwise returns false. Generally, the searching starts from the beginning of $subject string parameter.

What is greedy regex?

Greedy: As Many As Possible (longest match) For instance, take the + quantifier. It allows the engine to match one or more of the token it quantifies: \d+ can therefore match one or more digits. But "one or more" is rather vague: in the string 123, "one or more digits" (starting from the left) could be 1, 12 or 123.


1 Answers

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

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

/^Overview:\s.*$/im 

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.

like image 194
Niet the Dark Absol Avatar answered Sep 30 '22 23:09

Niet the Dark Absol