I have a string to check and if it is only numbers and digits perform another action else exit;
$data = 123412347JB91742F;
if(preg_match('/[A-Z1-9]/', $data )) {
echo $data;
}
else {
exit;
}
this works fine but if I add anything to $data like $ or any other thing it still prints the value. What is wrong with this code?
Edit:
$data = preg_replace('/\-/', '', '1234-1234-JB91-8742F');
if(preg_match('/^[A-Z1-9]+$/', $data )) {
echo $data;
} else {
exit;
}
Your regex will match every string containing a digit or "normal" character.
$data needs to be in quotes.
Your code should look like this:
preg_match('/^[A-Z1-9]+$/', $data)
Do you want to match zeros as well as lower case characters? Then your regex should look like this:
preg_match('/^[A-Z0-9]+$/i', $data)
Your regular expression just checks if there is at least one character of that set. Try this regular expression instead:
/^[A-Z1-9]+$/
The anchors ^ and $ mark the start and end of the string.
Related
I have a form field that I want to check if the user submitted a correct pattern. I tried it this way.
// $car_plate should in XXX-1111, or XXX-111(three letters in uppercase followed by a dash and four or three numbers)
<?php
$car_plate = $values['car_plate'];
if (!preg_match('[A-Z]{3}-[0-9]{3|4}$', $car_plate)) {
$this->errors ="Pattern for plate number is XXX-1111 or XXX-111";
} else {
// code to submit
}
?>
The following car_plate numbers is in correct format (AAA-456, AGC-4567, WER-123). In this case it always return the error. What is the correct way?
alternative to TimoSta's answer.
/^[a-zA-Z]{3}-?\d{3,4}$/
this allows for user to enter letters in lowercase and to skip the dash
you can format the data later like this:
$input = 'abc1234';
if ( preg_match( '/^([a-zA-Z]{3})-?(\d{3,4})$/', $input, $matches ) )
{
$new_input = strtoupper( $matches[1] ) . '-' . $matches[2];
echo $new_input;
}
outputs: ABC-1234
Looks like you're a little bit off with your regular expression.
Try this one:
/^[A-Z]{3}-[0-9]{3,4}$/
In PHP, you have to enclose your regular expression with delimiters, in this case the slashes. In addition to that, {3|4} is not valid, the correct syntax is {3,4} as you can see in the docs covering repetition.
I am checking username entered by user
I'm trying to validate usernames in PHP using preg_match() but I can't seem to get it working the way I want it. I require preg_match() to:
accept only letters , numbers and . - _
i.e. alphanumeric dot dash and underscore only, i tried regex from htaccess which is like this
([A-Za-z0-9.-_]+)
like this way but it doesnt seem to work, it giving false for simple alpha username.
$text = 'username';
if (preg_match('/^[A-Za-z0-9.-_]$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
How can i make it work ?
i am going to use it in function like this
//check if username is valid
function isValidUsername($str) {
return preg_match('/[^A-Za-z0-9.-_]/', $str);
}
i tried answwer in preg_match() and username but still something is wrong in the regex.
update
I am using code given by xdazz inside function like this.
//check if username is valid
function isValidUsername($str) {
if (preg_match('/^[A-Za-z0-9._-]+$/' , $str)) {
return true;
} else {
return false;
}
}
and checking it like
$text = 'username._-546_546AAA';
if (isValidUsername($text) === true) {
echo 'good';
}
else{
echo 'bad';
}
You missed the +(+ for one or more, * for zero or more), or your regex only matches a string with one char.
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
hyphen - has special meaning inside [...] that is used for range.
It should be in the beginning or in the last or escape it like ([A-Za-z0-9._-]+) otherwise it will match all the character that is in between . and _ in ASCII character set.
Read similar post Including a hyphen in a regex character bracket?
Better use \w that matches [A-Za-z0-9_]. In shorter form use [\w.-]+
What is the meaning for your last regex pattern?
Here [^..] is used for negation character set. If you uses it outside the ^[...] then it represents the start of the line/string.
[^A-Za-z0-9.-_] any character except:
'A' to 'Z',
'a' to 'z',
'0' to '9',
'.' to '_'
Just put - at the last in character class and add + after the char class to match one or more characters.
$text = 'username';
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
function should be like this
function isValidUsername($str) {
return preg_match("/^[A-Za-z0-9._-]+$/", $str);
}
How to match any thing dosen't contain a specific word using RegExp
Ex:
Match any string doesn't contain 'aabbcc'
bbbaaaassdd // Match this
aabbaabbccaass // Reject this
If you're just after this sequence of characters, don't use a Regular Expression. Use strpos().
if (strpos('aabbaabbccaass', 'aabbcc') !== false) {
echo 'Reject this.'
}
Note: Be sure to read the warning in the manual about strpos() return values.
You can use negative lookahead:
(?!.*?aabbcc)^.*$
Live Demo: http://www.rubular.com/r/4Exbf7UdDv
PHP Code:
$str = 'aabbaabbccaass'; //or whatever
if (preg_match('/(?!.*?aabbcc)^.*$/', $str))
echo "accepted\n";
else
echo "rejected\n";
try this to avoid some sequences of letters :
^((?!aabbcc).)*$
try this:
if(preg_match('/aabbcc/', $string) == 0) {
[ OK ]
}
else {
[ NOT OK ]
}
You can use this to describe a substring that doesn't contain aabbcc:
(?>[^a]++|a(?!abbcc))*
for the whole string, just add anchors (^ $)
I need to check some words with preg_match. If the words contain numbers and ., I want to echo "ok".
Lets say i want to ckeck this :
4814.84dszs //ok
412.84.61.412 //ok
hello.4you //ok
welcome.user //not ok
481221222 // not ok
I have used this:
if (preg_match('/^[0-9][.]+$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
But it doesn't give me the exactly result which I looking for.
Try this :
if (preg_match('/(\d+\.)|(\.\d+)/', '4814.84dszs'))
{
echo 'ok';
}
^ -> indicates at the begining of the string
$ -> End of the string.
So your pattern says from start to end(Matching for whole string)
If you remove this it will match anywhere in the string not whole string.
$pattern = '#^([\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})([.][\d]{1,3})$#';
Use this:
if (preg_match('/([0-9]+[\.]+|[\.]+[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
"+" (plus sign) means 1 or more occurrences of the matched expression
You can also use this if the . and the numbers are not following each other and there are other chars in the middle:
if (preg_match('/([0-9]+[^0-9\.]*[\.]+|[\.]+[^0-9\.]*[0-9]+)$/', 'MY_WORD_HERE'))
{
echo 'ok';
}
Explanation: it checks if there is a digit followed by dot or if there's a dot followed by a digit or even if there's a digit followed by other chars then a dot or vice versa.
try using this
$pattern = '%(?=.*[0-9])(?=.*\.)%';
if (preg_match($pattern, 'MY_WORD_HERE'))
{
echo 'ok';
}
?>
I have a part of a function that goes like this:
if (preg_match("#\bscript\b#",$userInput))
{
$bannedWord = 'script';
logHax();
return TRUE;
}
This is causing a problem for what I am trying to accomplish because it will only match the exact word "script" and not variations of it, like "ScriPt" or "<script>".
What I would like to have is the examples of the not matched strings along with the original string return true.
How's this:
if (preg_match("/<script\b[^>]*>/i",$userInput))
{
$bannedWord = 'script';
logHax();
return TRUE;
}
Case-insensitive matching:
preg_match("#\bscript\b#i",$userInput)
Note the i. Also note that this the first example in the docs:
<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
Cheers
If you really want to match "anything" before or after the string (not just a word), then you do not even need preg_match here, bacuse you could do something like this:
$userInputLower = strtolower($userInput);
if (strpos($userInputLower, 'script') !== false)
{
$bannedWord = 'script';
logHax();
return TRUE;
}