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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With