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/ | |||||||||||
| |||||||||||
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]; } | |||||||||||
| |||||||||||
| |||||||||||
![]() ![]() ![]() ![]() | |||||||||||
2022 AnswerTabs | Terms | Contact us |