How to user pregmatch in php - php

I am trying to find if a persons name contains any numbers or symbols. I am not very sure how to use preg_match and all the examples online make no sense can someone please explain how i can check if a value has numbers or symbols. And if you can please explain how it works.

To check if the person name contains only number. The code below has been tested and is working
<?php
error_reporting(0);
$number = '001222288';
if (!preg_match('/^[0-9]*$/', $number)) {
//error
echo 'Error does not contain only number';
} else {
echo 'success. it contains only number';
}
?>
if the variable number contains any other thing that is not number it result in error. eg
$number = 'ABFRT001222288';
To check for alphabets or string
<?php
error_reporting(0);
$string = 'ABTYUUU';
if (!preg_match('/^[A-Z]*$/', $string)) {
//error
echo 'Error does not contain only alphabet';
} else {
echo 'success. it contains only alphabets';
}
?>
Mark this as correct answer if it solve your problem
Thanks

The function preg_match use regex expressions. You can use an online tool for test your regex. I use debuggex, preg_match use PCRE expressions. In your case you should, you may use for numbers
preg_match("/[0-9]+/", $subject);
EDIT : We need more details for the symbols you want select

Related

PHP "preg_match" to check whether the text contains small characters [duplicate]

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.

how to check if string contains square brackets php

I have a strange question maybe you could help me with. I am trying to check whether the given string contains special characters. The code below is working however one character seems to get exempted on the condition which is the square brackets [ ]. Can you help me with this? thank you.
$string = 'starw]ars';
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $string)) {
echo 'Output: Contains Special Characters';
}else{
echo 'Output: valid characters';
}
Please note: I can't use below condition since I need to accept others characters from other languages like in arabic, chinese, etc. so it means I need to specify all characters that is not allowed.
if (!preg_match('/[^A-Za-z0-9]/', $string))
Appreciate your help. Thanks.
You forgot to add square brackets [] in your expression. I have added this \[\] in your current expression.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string = 'starw]ars';
if (preg_match('/[\[\]\'^£$%&*()}{##~?><>,|=_+¬-]/', $string))
{
echo 'Output: Contains Special Characters';
} else
{
echo 'Output: valid characters';
}
Use strpos:
$string = 'starw]ars';
if (strpos($string, ']') !== false) {
echo 'true';
}
Please see the following answer for additional information:
How do I check if a string contains a specific word in PHP?
You should add escaped square brackets to your expression.
preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-\[\]]/', $string)
EDIT: Apologies to #Thamilan, I didn't see your comment.
EDIT 2: You could also use the preg_quote function.
preg_match(preg_quote('\'^£$%&*()}{##~?><>,|=_+¬-[]', '/'), $string);
The preg_quote function will escape your special characters for you.
Try this example:
<?php
$string = 'starw]]$%ars';
if (preg_match('/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $string))
{
echo 'Output: Contains Special Characters';
} else
{
echo 'Output: valid characters';
}
?>
Output:
Output: Contains Special Characters

String cannot start with zero

I have a string which i want to check with a regex. It is not allowed for it to start with a 0. So please see the following examples:
012344 = invalid
3435545645 = valid
021 = invalid
344545 = valid
etc.
How does this regex look in PHP?
PS. This must be a regex solution!
The REGEX should looks like that :
^[1-9][0-9]*$
PHP Code :
<?php
$regex = "#^[1-9][0-9]*$#";
function test($value, $regex)
{
$text = "invalid";
if(preg_match($regex, $value)) $text = "valid";
return $value+" = "+$text+"\n\r";
}
echo test('012345', $regex);
echo test('12345', $regex);
?>
Well it would be a simple /[1-9][0-9]*/.
Please research your question better next time.
This could have also helped you: Regular expression tester
Edit:
Yeah, the answer got downvoted, because it's missing the anchors and seems to be wrong. For completess' sake, I posted the php code I would use with this regex. And no it's not wrong. It may not be the most elegant way, but I like checking whether the regex matched the whole string afterwards more. One reason is that to debug a regex and see what it actually matched I just have to comment out === $value after return $matches[0]
<?php
function matches($value) {
preg_match("/[1-9][0-9]*/", $value, $matches);
return $matches[0] === $value;
}
//Usage:
if (matches("1234")) {
//...
}
?>

PHP string validation - Firstname_Lastname

I'd like to get some help regarding PHP.
Let's say I have a string ($fullname).
I want to validate that it's in the form of "Firstname_Lastname".
For example, make sure that it's "Nathan_Phillips" and not "Nathan Phillips" or "Nathan122" etc.
Can you guys help me with the function?
Thanks in advance! :-)
------------ EDIT -------------
Thank you guys! Managed to do that. Also added the numbers filter. Here's the function:
function isValidName($name)
{
if (strcspn($name, '0123456789') != strlen($name))
return FALSE;
$name = str_replace(" ", "", $name);
$result = explode("_", $name);
if(count($result) == 2)
return TRUE;
else
return FALSE;
}
Usage example:
if(isValidName("Test_Test") == TRUE)
echo "Valid name.";
else
echo "Invalid name.";
Thanks again!
Maybe try something like this:
function checkInput($input) {
$pattern = '/^[A-Za-z]{2,50}_[A-Za-z]{2,50}/';
return preg_match($pattern, substr($input,3), $matches, PREG_OFFSET_CAPTURE);
}
This will accept a string containing 2-50 alphabetic characters, followed by an underscore, followed by 2-50 alphabetic characters.
I'm not the best with regex, so I invite corrections if anyone sees a flaw.
If you have special characters (è, í, etc.), the regex I gave probably won't accept it. Also, it won't accept names like O'Reilly or hyphenated names. See this:
Regex for names
I'll let you track down all the exceptions to the regex for names, but I definitely think regex is the way to go.

preg_match with international characters and accents

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.

Categories