Reputation: 2141
I need to write a regexp that matches a string that has only numbers in it and these numbers can be divided by a comma or dash or underline or slash/backslash.
For example:
$reg = '/^\d+$/';
$phoneWithDashes = '343-1431-4412';
$phoneWithoutDashes = '34314314412';
echo preg_match($reg, $phoneWithDashes); // 0
echo preg_match($reg, $phoneWithoutDashes); // 1
How do I tell to this regexp '/^\d+$/' that I also want to match if there are dashes anywhere in the string?
Upvotes: 0
Views: 34
Reputation: 19493
Since dashes can appear anywhere (between 2 digits), I would split on the dashes then check each string individually. Let's see how that translates to PHP code.
function match_phone($phone) {
$arr = preg_split('/[\/\\-_,]/', $phone);
$reg = '/^\d+$/';
foreach ($arr as $str) {
if (!preg_match($reg, $str)) {
return 0;
}
}
return 1;
}
echo match_phone('343-1431-4412/7'); // 1
echo match_phone('343143144127'); // 1
echo match_phone('1234-illegal'); // 0
echo match_phone('11--22'); // 0
Upvotes: 2