Reputation: 85
Supposing there's an array as the following:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
and I just need the elements that contains 4 characters in total only. So except for foo12345bar, other 3 elements are valid.
Because '\d{4}'
would match foo12345bar, so I try following clumsily:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
$result = array();
foreach ($arr as $value) {
preg_match('/\d+/', $value, $match);
if (strlen($match[0]) != 4) {
continue;
}
$result[] = $value;
}
var_dump($result); //array('foo1234bar', 'foo1234', '1234bar')
Is there a regular expression to match directly(so the if condition can be omitted)? Thank you in advance.
Upvotes: 2
Views: 86
Reputation: 11689
This regular expression will work on all your examples:
'/^\D*(\d{4})\D*$/'
││ │ │ └── end string
││ │ └───── zero or more NOT digits
││ └─────────── four digits ( match 1 )
│└─────────────── zero or more NOT digits
└──────────────── start string
They doesn't work if there are multiple number group in the string ( '123abc1234o' ).
Upvotes: 0
Reputation: 29912
Modify your regex as follows
/^\D*\d{4}\D*$/
^
your string must start with
\D
any non-digit char
*
repeated from 0 to infinite times
\d{4}
followed by any digit repeated EXACTLY 4 times
\D
followed by any non-digit char
*
repeated from 0 to infinite times
$
end of the string
Moreover you could modify your code as follows
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
$result = array_filter(
$arr,
function($element) {
return preg_match('/^\D*\d{4}\D*$/', $element);
}
);
var_dump($result);
As OP didn't specify it, this regex will match even 1234 (any four digit string without non-digit chars in front or behind). If he wishes to have at least a char in front or/and behind, this regex must be changed.
Upvotes: 1
Reputation: 785146
This easy to handle with look-around regex and preg_grep
function:
$arr = array('foo1234bar', 'foo1234', '1234bar', 'foo12345bar');
print_r(preg_grep('/(?<!\d)\d{4}(?!\d)/', $arr));
RegEx Breakup:
(?<!\d) # assert previous char is not a digit
\d{4} # match exact 4 digits
(?!\d) # assert next char is not a digit
Output:
Array
(
[0] => foo1234bar
[1] => foo1234
[2] => 1234bar
)
Upvotes: 5
Reputation: 11807
Assuming the characters in front of and after the numbers will always be alphabetical, you can use this regex:
^[a-zA-Z]*\d{4}[a-zA-Z]+$
Upvotes: 1
Reputation: 96
you might try folowing :
preg_match('/\D\d{4}\D/', $value, $match);
it searches for:
a not digit(/D)
4 digits(/d{4})
again a non digit(/D)
Upvotes: 0
Reputation: 1230
the regexp will be \d{4}
preg_match('/\d{4}/', $value, $match);
expect will help
Upvotes: 0