Reputation: 1981
I'm using this code to validate string.
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
How if I want to validate if the number contain "+" sign in front or not?
Such as :
$countrecipient ='+0123456789';
and still need to validate the rest of the string.
I tried this:
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
{
echo "Ok";
}
else
{
echo "Error";
}
It works in my pc but I'm not sure why my customer is complaining it shows him error.
Thank you.
Upvotes: 0
Views: 183
Reputation: 1477
Based on regexp you put in the section you tried: "...preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/'..."
If you would validate the string AND check if there is a '+' or not, you could use something like this:
if(preg_match('/(\+)?6011[0-9][0-9]{7}?$/', $countrecipient, $matches))
{
if ($matches[1] == '+') {
echo "Ok WITH PLUS";
} else {
echo "Ok without PLUS";
}
}
else
{
echo "Error";
}
Upvotes: 1
Reputation: 57650
The simplified form of your regex is
/\+?01[0-9]{8}/
However I recommend you use intval, is_int, ctype_digit to accomplish this.
if(intval($str)<=100000000){
// found it.
}
Upvotes: 1
Reputation: 20997
Plus has a special meaning in PCRE, it's called quantifier and has meaning of {1,}
.
You may either put in into character group specification like this [+]
which would literally mean one of following characters: array( '+')
or escape it with \
so you'll get: \+
.
Also adding {1}
is implicit and you don't have to add it after one character. If you were doing this matching foo
would look like: f{1}o{1}o{1}
, ehm f{1}o{2}
instead of foo
:)
If you want to match both 0123456789
and +012345678
you should use {0,1}
which has "shortcut" ?
. Than your pattern would look like: /\+?/
. I guess your desired regexp is:
/^\+?0?1?[0-9]([0-9]{7})?$/
Upvotes: 1
Reputation: 106086
$countrecipient ='0123456789';
preg_match('/^[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient)
You're making things unnecessarily complicated. "[0]{1}[1]{1}[0-9]{1}" reduces to simply "01[0-9]".
To have an optional + on the front, your basic idea of using [+] should work. Let's see...
$countrecipient ='+0123456789';
if(preg_match('/^[+]{1}[6]{1}[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient))
...again this can be simplified, but it simplies to /^[+]601[0-9][0-9]{7}?$/
. Where did the 6
after the +
come from? Does this account for your problem?
Upvotes: 1
Reputation: 21553
For an optional plus in front you could use:
preg_match('/^\+?[0]{1}[1]{1}[0-9]{1}[0-9]{7}?$/', $countrecipient);
Notice how I have escaped the +
with a backslash? This is because it is a regex keyword which means 1 instance or more.
Upvotes: 1