Regex pattern to get the shortest / longest possible match

How to create a regex pattern to match minimum or maximum number of characters ? For example to get the shortest or longest possible match from the string below. How to modify the regular expression pattern to get only value "123" or value "123/456/789".

/123/456/789/
0
give a positive ratinggive a negative rating
12 Jan 2020 at 03:50 PM
Hi,

To get the shortest or longest possible match with regular expression, you need to create a pattern with greedy or non greedy matching. The pattern matching can be changed to non greedy, that is also known as lazy, by adding ? into the code. For example:


This pattern will get the longest possible match. The result will be 123/456/789.
$string = "/123/456/789/";
if(preg_match("/\/(.+)\//", $string, $match)){ echo "Greedy matching: " . $match[1]; }


This pattern will get the shortest possible or lazy match. The result will be 123.
$string = "/123/456/789/";
if(preg_match("/\/(.+?)\//", $string, $match)){ echo "Non greedy matching: " . $match[1]; }

0
give a positive ratinggive a negative rating
13 Jan 2020 at 07:23 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us