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/
posted on 12.01.2020 at 15:50
0pnshow more
StorStor
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]; }

posted on 13.01.2020 at 19:23
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.