Sorry for asking this simple question, but I seem not to find any answers.
How can you check whether there is a number within a string?
I've tried:
$string = "this is a simple string with a number 2432344";
if (preg_match('/[^0-9]/', "$string")) {
echo "yes a number";
} else {
echo "no number";
}
Doesn't seem to work...
If you want to find a number, don't negate the character set with ^ in your regular expression. That means "match anything except a number".
$string = "this is a simple string with a number 2432344";
if (preg_match('/[0-9]/', "$string")) {
echo "yes a number";
} else {
echo "no number";
}
Also, you could just use \d instead of [0-9], and $string instead of "$string".
^ will only negate what's in the regex. You don't need to use it.
Related
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
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
This code works to allow only alphanumeric characters but I want to prevent $name from starting with a number. How do I do this?
$name = "007_jamesbond";
if(preg_match('/[^a-z_\-0-9]/i', $name)){
echo "invalid name";
}
This should do it. Also \w is alphanumeric characters and underscores.
$name = "007\_jamesbond";
if(preg_match('/(^\d|[^\-\w])/', $name)){
echo "invalid name";
}
Output:
invalid name
Regex101 Demo: https://regex101.com/r/dF0zQ1/1
Update
Should account for decimals and negative numbers as well...
$name = "007\_jamesbond";
if(preg_match('/(^[.\-]?\d|[^\-\w])/', $name)){
echo "invalid name";
}
Demo: https://regex101.com/r/dF0zQ1/2
It may be clearer to define a pattern for what is valid, and check for things that do not match it.
if(!preg_match('/^[a-z][a-z_\-0-9]*/i', $name)){
echo "invalid name";
}
// ^ anchor to beginning of string
// [a-z] a letter (add underscore here if it's ok too)
// [a-z_\-0-9]* any number of alphanumeric+underscore characters
$name = "007_jamesbond";
if(preg_match('/^[^a-z]/i', $name)){
echo "invalid name";
}
The ^ at the start of a regex means "The start of the string". This regex can be read as: "If $name starts (^) with a character that is not a-z ([^a-z]), it is invalid."
If you want a single regex to match both requirements ("only alphanum, doesn't start with non-letter"), you can use this:
/(^[^a-z]|[^\w\-])/
Try this: (without using regex)
$first = substr($name, 0,1);
if(is_numeric($first))
{
echo 'the first character cannot be numeric';
}
else
{
if(preg_match('/[^a-z_\-0-9]/i', $name))
{
echo 'invalid name';
}
}
<?php
$flag=true;
if(isset($_POST['sub'])){
if(isset($_POST['text'])){
$a=$_POST["text"];
} else {
$a='';
}
if(!empty($_POST['msg'])){
$b=$_POST['msg'];
$c=strlen($b);}
if(isset($_POST['wrd'])){
$d=($_POST["wrd"]);
} else {
$d='';
}
if(preg_match("[\w\s.,a-zA-Z$a,\.]",$b)){
$flag=false;
}
if($flag){
$i;
for($i=0;$i<=$c;$i++)
{
$newtext = str_replace($a,$d,$b);
echo $newtext;
echo "</br>";
break;
}
} else {
echo"not found ";}
}
?>
This is my code I want to match word(paragraph) from a original paragraph but the problem is this.
In one line the word (paragraph) is written like this (paragraph,) and (paragraph.)
That's why preg_match is not able to find the these two word and same goes to preg_replace also.
This is incorrect:
if(preg_match("[\w\s.,a-zA-Z$a,\.]",$b))
Regex needs start and end delimiters. It should be:
if(preg_match("/[\w\s.,a-zA-Z$a,\.]/", $b))
Also note that your regex is also incorrect. I can see few mistakes (there myay be more):
inside square brackets you don't need to escape dot
you seem to have another dot that will match ANY character
You have \w that means word character hence you don't need separate a-zA-Z
You have a misplaced a after $ sign
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.