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.
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.
$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?
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})?$/
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.
}
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";
}
Related
I would like to validate a string with a pattern that can only contain letters (including letters with accents). Here is the code I use and it always returns "nok".
I don't know what I am doing wrong, can you help? thanks
$string = 'é';
if(preg_match('/^[\p{L}]+$/i', $string)){
echo 'ok';
} else{
echo 'nok';
}
Add the UTF-8 modifier flag (u) to your expression:
/^\p{L}+$/ui
There is also no need to wrap \p{L} inside of a character class.
I don't know if this helps anybody that will check this question / thread later. The code below allows only letters, accents and spaces. No symbols or punctuation like .,?/>[-< etc.
<?php
$string = 'États unis and états unis';
if(preg_match('/^[a-zA-Z \p{L}]+$/ui', $string)){
echo 'ok';
} else{
echo 'nok';
}
?>
If you want to add numbers too, just add 0-9 immediately after Z like this a-zA-Z0-9
Then if you are applying this to form validation and you are scared a client/user might just hit spacebar and submit, just use:
if (trim($_POST['forminput']) == "") {... some error message ...}
to reject the submission.
I don't know almost anything about regex, but I need to allow only one space between letters, this is what I have done with another questiona and answer, plus random tries with regex101:
/^(\d){1,}(\:[A-Za-z0-9-]+([ a-zA-Z0-9-]+)?)?\:(\d){1,}(?:\.(\d){1,2})?$/m
The fomat should be:
[integer]:[optional label :][integer/decimal]
Example:
12:aaa:12.31
56:a s f:15
34:45.8
I have done some random tries without any success,I'm only able to allow infinite space, could someone help me? I have also looked at others answers, but I couldn't implement in my regex.
Check if error:
preg_match_all('/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/mi', $_POST['ratetable'], $out);
if($out[0]!=explode("\n",$_POST['ratetable'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array(0=>'Invalid price table at line: '.implode(", ", array_diff_key(array_flip(explode("\n",$_POST['ratetable'])),array_flip($out[0])))));
exit();
}
You could make the regex a bit shorter and allow a single space in between each letter like this:
/^(\d+)(:[A-Z0-9-]+(?: [A-Z0-9-]+)*)?:(\d+(?:\.\d{1,2})?)$/gmi
regex101 demo
If you want to capture only the label (and exclude the :) in the capture, you can use this one.
I think
^\d+:([^:]+:)?\d+(\.\d+)?$
might do it...
It means: <int> + ":" + [label + ":"] + <float> where label can be anything but :.
You're nearly there:
(?: [a-zA-Z0-9-]+)*
the above would mean: space followed by at least one in the character group; the latter group any number of times, without capturing
You can use preg_match
$str = 'Another Example String 1_2-3';
echo $str . "<br />\n";
if (preg_match('#^(?:[\w-]+ ?)+$#', $str)){
echo 'Legal format!';
} else {
echo 'Illegal format!';
}
^\d+:([\w\d]+ ?)*:?\d+(\.\d+)?$
Live demo
Morning SO. I'm trying to determine whether or not a string contains a list of specific characters.
I know i should be using preg_match for this, but my regex knowledge is woeful and i have been unable to glean any information from other posts around this site. Since most of them just want to limit strings to a-z, A-Z and 0-9. But i do want some special characters to be allowed, for example: ! # £ and others not in the below string.
Characters to be matched on: # $ % ^ & * ( ) + = - [ ] \ ' ; , . / { } | \ " : < > ? ~
private function containsIllegalChars($string)
{
return preg_match([REGEX_STRING_HERE], $string);
}
I originally wrote the matching in Javascript, which just looped through each letter in the string and then looped through every character in another string until it found a match. Looking back, i can't believe i even attempted to use such an archaic method. With the advent of json (and a rewrite of the application!), i'm switching the match to php, to return an error message via json.
I was hoping a regex guru could assist with converting the above string to a regex string, but any feedback would be appreciated!
Regexp for a "list of disallowed character" is not mandatory.
You may have a look at strpbrk. It should do the job you need.
Here's an example of usage
$tests = array(
"Hello I should be allowed",
"Aw! I'm not allowed",
"Geez [another] one",
"=)",
"<WH4T4NXSS474K>"
);
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";
foreach ($tests as $test) {
echo $test;
echo ' => ';
echo (false === strpbrk($test, $illegal)) ? 'Allowed' : "Disallowed";
echo PHP_EOL;
}
http://codepad.org/yaJJsOpT
return preg_match('/[#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/', $string);
$pattern = preg_quote('#$%^&*()+=-[]\';,./{}|\":<>?~', '#');
var_dump(preg_match("#[{$pattern}]#", 'hello world')); // false
var_dump(preg_match("#[{$pattern}]#", 'he||o wor|d')); // true
var_dump(preg_match("#[{$pattern}]#", '$uper duper')); // true
Likely, you can cache the $pattern, depending on your implementation.
(Though looking outside of regular expressions, you're best of with strpbrk as mentioned here too)
I think what you're looking for can be greatly simplified by including the characters that you want to allow like so:
preg_match('/[^\w!#£]/', $string)
Here's a quick breakdown of what's happening:
[^] = not included
\w = letters and numbers
! # £ = the list of characters you would also like to allow
I am trying to get this Regex to work to validate a Name field to only allow A-Z, ' and -.
So far I am using this which is working fine apart from it wont allow an apostrophe.
if (preg_match("/[^a-zA-Z'-]+/",$firstname)) {
// do something
}
I would like it to only allow A-Z, - (dash) and an ' (apostrophe). It works for the A-Z and the - but still wont work for the '
Could someone please provide an example?
Thanks
if (preg_match("/^[A-Z'-]+$/",$firstname)) {
// do something
}
The caret ^ inside a character class [] will negate the match. The way you have it, it means if the $firstname contains characters other than a-z, A-Z, ', and -.
Your code already does what you want it to:
<?php
$data = array(
// Valid
'Jim',
'John',
"O'Toole",
'one-two',
"Daniel'Blackmore",
// Invalid
' Jim',
'abc123',
'$##$%##$%&*(*&){}//;;',
);
foreach($data as $firstname){
if( preg_match("/[^a-zA-Z'-]+/",$firstname) ){
echo 'Invalid: ' . $firstname . PHP_EOL;
}else{
echo 'Valid: ' . $firstname . PHP_EOL;
}
}
... prints:
Valid: Jim
Valid: John
Valid: O'Toole
Valid: one-two
Valid: Daniel'Blackmore
Invalid: Jim
Invalid: abc123
Invalid: $##$%##$%&*(*&){}//;;
The single quote does not have any special meaning in regular expressions so it needs no special treatment. The minus sign (-), when inside [], means range; if you need a literal - it has to be the first or last character, as in your code.
Said that, the error (if any) is somewhere else.
"/[^a-zA-Z'-]+/" actually matches everything but a-zA-z'-, if you put the ^ in to indicate the start-of-string, you should put it outside the brackets.
Also, the '- part of your expression is possibly being interpreted as a range, so you should escape the - as #Tom answered or escape the , as someone else answered
From what I see. Following Regex should work fine:
if (preg_match("/^[A-Z\'\-]+$/",$firstname)) {
// do something
}
Here I have escaped both apostrophe and dash. I have tested this in an online Regex tester and works just fine.
Give it a try
Your regexp should look like this:
preg_match("/^[A-Z\'-]+$/",$firstname);
maches: AB A-B AB-'
does not match: Ab a-B AB# <empty string>
if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
// do something here
}
I have used this, This will work fine. Use It.
I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1, 2, 3, etc.) without non-digit characters.
My method looks like this:
function is_natural($str)
{
return preg_match('/[^0-9]+$/', $str) ? false : $str;
}
So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3" and even "2.3,2.2"
perhaps you can clarify the difference between a "number" and a "digit" ??
Anyways, you can use
if (preg_match('/^[0-9]+$/', $str)) {
// contains only 0-9
} else {
// contains other stuff
}
or you can use
$str = (string) $str;
ctype_digit($str);
The problem with /^[0-9]+$/ is that it also accepts values like 0123.
The correct regular expression is /^[1-9][0-9]*$/.
ctype_digit() suffers the same problem.
If you also need to include zero use this regex instead: /^(?:0|[1-9][0-9]*)$/
Use ctype_digit() instead
I got an issue with ctype_digit when invoice numbers like "000000196" had to go through ctype_digit.
So I have used a:
if (preg_match('/^[1-9][0-9]?$/', $str)) {
// only integers
} else {
// string
}