Here are my two cents:
\d{4,}(*SKIP)(*FAIL)|(\d{3})
An example of a regular expression is here .
It means:
\d{4,}(*SKIP)(*FAIL) -> match 4 digits or more but skip the match | -> Or (\d{3}) -> match 3 digits and capture it.
This means that your regular expression will match ONLY the occurrences of the three digits in the captured group.
Hope this helps.
EDIT :
Added (*SKIP)(*FAIL) verbs.
These two verbs force the compromise of a match. And then a replacement can be made. (See the replacement part of regex101 example.)
In php, the code would look like this:
$arr = array( "a 123 234 b", "a 123_234 b", "aa123 234 b", "a0123 234 b", "123a234 b", "a 123 234" ); $regex = "/\d{4,}(*SKIP)(*FAIL)|(\d{3})/"; foreach ($arr as $item) { echo preg_replace($regex, '<a href="#">$1</a>', $item); echo "\r\n"; }
Output:
a <a href="#">123</a> <a href="#">234</a> b a <a href="#">123</a>_<a href="#">234</a> b aa<a href="#">123</a> <a href="#">234</a> b a0123 <a href="#">234</a> b <a href="#">123</a>a<a href="#">234</a> b a <a href="#">123</a> <a href="#">234</a>
source share