Im creating a search function. The users are only allowed to use a-z A-Z and 0-9. How do i check if $var only contains text or numbers, and not special characters ?
I have tried something like this:
if (!preg_match('/[^a-z]/i', $search) {
$error = "error...";
}
If anyone have a smarter solution, please let me know. It could also be something checking for special characters.
You're pretty much there. Just add numbers 0-9 to your regular expression, like this:
if(preg_match('/[^a-z0-9]/i', $search))
{
$error = "Error...";
}
The /i flag tells the expression to ignore case, so A-Z is not needed inside the letter list.
In your original code, you were looking for anything that wasn't a letter or number, while also checking to see if preg_match() hadn't matched anything - you created a double negative. The code above executes the if() if anything that isn't a letter or number is found. Full credit to #brain in the comments.
To allow other characters, simply add them to the characters inside the braces:
if(preg_match('/[^a-z0-9 \.]/i', $search))
{
$error = "Error...";
}
This example allows spaces and . (dots).
Something like this:
if(!preg_match('/^[a-zA-Z0-9]+$/', $search)) {
// error
}
Related
I try to make system that can detect date in some string, here is the code :
$string = "02/04/16 10:08:42";
$pattern = "/\<(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}\>/";
$found = preg_match($pattern, $string);
if ($found) {
echo ('The pattern matches the string');
} else {
echo ('No match');
}
The result i found is "No Match", i don't think that i used correct regex for the pattern. Can somebody tell me what i must to do to fix this code
First of all, remove all gibberish from the pattern. This is the part you'll need to work on:
(/0?[1-9]|[12][0-9]|3[01]/)
(As you said, you need the date only, not the datetime).
The main problem with the pattern, that you are using the logical OR operators (|) at the delimiters. If the delimiters are slashes, then you need to replace the tube characters with escaped slashes (/). Note that you need to escape them, because the parser will not take them as control characters. Like this: \/.
Now, you need to solve some logical tasks here, to match the numbers correctly and you're good to go.
(I'm not gonna solve the homework for you :) )
These articles will help you to solve the problem tough:
Character classes
Repetition opetors
Special characters
Pipe character (alternation operator)
Good luck!
In your comment you say you are looking for yyyy, but the example says yy.
I made a code for yy because that is what you gave us, you can easily change the 2 to a 4 and it's for yyyy.
preg_match("/((0|1|2|3)[0-9])\/\d{2}\/\d{2}/", $string, $output_array);
Echo $output_array[1]; // date
Edit:
If you use this pattern it will match the time too, thus make it harder to match wrong.
((0|1|2|3)[0-9])/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}
http://www.phpliveregex.com/p/fjP
Edit2:
Also, you can skip one line of code.
You first preg_match to $found and then do an if $found.
This works too:
If(preg_match($pattern, $string, $found))}{
Echo $found[1];
}Else{
Echo "nothing found";
}
With pattern and string as refered to above.
As you can see the found variable is in the preg_match as the output, thus if there is a match the if will be true.
I'm trying to find a good preg_match expression that allow all letters (included accented letters), the space , and these symbols: - '
I thought this could be a good solution '/^\p{L}+$/ui', but I can't find a successful way to add the symbols I need, if that is possible...
Otherwise I guess I should use something like this:
'#^[a-zA-Z0-9àòäöüÄÖÜ \.\]]+$#'
but there are so many accents that I was hoping to find a better solution.
Try placing the \p{L} and allowed symbols inside brackets:
$name = "B-jör n'Bòrg";
if (preg_match("/^[- '\p{L}]+$/u", $name)) {
echo "$name is a valid name!"; // It is
}
You may also want to add some additional checks, e.g. to make sure that names starts and ends with a letter and not a symbol.
Edit
This will make sure that names starts/ends with a letter and does not contain consecutive symbols:
$name = "-Björ n''Bòrg-";
if (preg_match("/^\p{L}([- ']\p{L}|\p{L})*$/u", $name)) {
echo "$name is a valid name!"; // It's not
}
I'm having a some trouble formatting my regular expression for my PHP code using preg_match().
I have a simple string usually looking like this:
"q?=%23asdf".
I want my regular expression to only pass true if the string begins with "q?=%23" and there is a character at the end of the 3. So far one of the problems I have had is that the ? is being pulled up by the regex so doing something like
^q?=23 doesn't work. I am also having problems with contiguous searching in Regex expressions (because I can't figure out how to search after the 3).
So for clarification: "q?=%23asd" should PASS and "q?=%23" should FAIL
I'm no good with Regex so sorry if this seems like a beginner question and thanks in advance.
Just use a lookahead to check whether the character following 3 is an alphabet or not,
^q\?=%23(?=[a-zA-Z])
Add . instead of [A-Za-z] only if you want to check for any character following 3,
^q\?=%23(?=.)
Code would be,
$theregex = '~^q\?=%23(?=[a-z])~i';
if (preg_match($theregex, $yourstring)) {
// Yes! It matches!
}
else { // nah, no luck...
}
So the requirement is: Start with q?=%23, followed by at least one [a-z], the pattern could look like:
$pattern = '/^q\?=%23[a-z]+/i';
Used i (PCRE_CASELESS) modifier. Also see example at regex101.
$string = "q?=%23asdf";
var_dump(figureOut($string));
function figureOut($string){
if(strpos($string, 'q?=%23') == 0){
if(strlen($string) > 6){
return true;
}else{ return false;}
}
}
I'm trying to make a regex that would allow input including at least one digit and at least one letter (no matter if upper or lower case) AND NOTHING ELSE. Here's what I've come up with:
<?php
if (preg_match('/(?=.*[a-z]+)(?=.*[0-9]+)([^\W])/i',$code)) {
echo "=)";
} else {
echo "=(";
}
?>
While it gives false if I use only digits or only letters, it gives true if I add $ or # or any other non-alphanumeric sign. Now, I tried putting ^\W into class brackets with both a-z and 0-9, tried to use something like ?=.*[^\W] or ?>! but I just can't get it work. Typing in non-alphanums still results in true. Halp meeee
You need to use anchors so that it matches against the entire string.
^(?=.*[a-z]+)(?=.*[0-9]+)(\w+)$
Since you are using php, why even use regex at all. You can use ctype_alnum()
http://php.net/manual/en/function.ctype-alnum.php
I want a regular expression to validate a nickname: 6 to 36 characters, it should contain at least one letter. Other allowed characters: 0-9 and underscores.
This is what I have now:
if(!preg_match('/^.*(?=\d{0,})(?=[a-zA-Z]{1,})(?=[a-zA-Z0-9_]{6,36}).*$/i', $value)){
echo 'bad';
}
else{
echo 'good';
}
This seems to work, but when a validate this strings for example:
11111111111a > is not valid, but it should
aaaaaaa!aaaa > is valid, but it shouldn't
Any ideas to make this regexp better?
I would actually split your task into two regex:
to find out whether it's a valid word: /^\w{6,36}$/i
to find out whether it contains a letter /[a-z]/i
I think it's much simpler this way.
Try this:
'/^(?=.*[a-z])\w{6,36}$/i'
Here are some of the problems with your original regex:
/^.*(?=\d{0,})(?=[a-zA-Z]{1,})(?=[a-zA-Z0-9_]{6,36}).*$/i
(?=\d{0,}): What is this for??? This is always true and doesn't do anything!
(?=[a-zA-Z]{1,}): You don't need the {1,} part, you just need to find one letter, and i flag also allows you to omit A-Z
/^.*: You're matching these outside of the lookaround; it should be inside
(?=[a-zA-Z0-9_]{6,36}).*$: this means that as long as there are between 6-36 \w characters, everything else in the rest of the string matches! The string can be 100 characters long mostly containing illegal characters and it will still match!
You can do it easily using two calls to preg_match as:
if( preg_match('/^[a-z0-9_]{6,36}$/i',$input) && preg_match('/[a-z]/i',$input)) {
// good
} else {
// bad
}