what is the proper way of using an if condition with RegEx - php

I have been trying to validate a form where the input is the first and last name using regex in PHP. All I need the regex to do is check to make sure that there are no numbers. This is what I have right now:
if (preg_match('/\A\b[^0-9]*\W[^0-9]*\b\Z/sm', $name)) {
# Successful match
$nameError = "";
echo $name;
} else {
# Match attempt failed\
$nameError = "No Numbers";
}
The $name variable holds First and last name. I have been trying to make this work and I have not been able to get the input to match the regex. Am I using this correctly or do I need to input it in another way. Thank you for your help

if name is surename and first name you should use condition depending on country for example in Poland it would be
preg_match('/[a-z]+ [a-z]+/i',$name);
It means that all the names that contains two part that are alphabetic with space separating them are good. If you want first letter of name to be upper you should change it to
preg_match('/[A-Z][a-z]+ [A-Z][a-z]+/',$name);
Preg_match returns true if $name is validated by regular expression that you provide in the first argument.
So your usage of this function is okay, you should check your expression.
http://pl1.php.net/preg_match
preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
You can always check your regex on online checker for example
http://www.solmetra.com/scripts/regex/

If you just want two words separated by one space, this will do what you want: if (preg_match('/^[A-Za-z]+ [A-Za-z]+$/', $name))

Thank you all for your replies, I found the answer in the most obvious place though and it didn't have anything to do with the regex. I forgot to setup the variables correctly for using them on the same page as the form. Stupid mistake. Anyway, thank you again.

Related

regex validation not parsing string in if PHP

Here is the deal...
I am suppose to parse a Canadian Postal Code (CapsLetterNumberCapsLetterNumberCapsLetterNumber: exemple A1B2C3 or G2V3V4)
IF there is one.
I have this code (PHP):
//Create new SESSION variable to store a warning
$_SESSION['msg'] = "";
//IF empty do nothing, IF NOT empty parse, IF NOT match regex put message in msg
if(!preg_match('^([A-Z][0-9][A-Z][0-9][A-Z][0-9])?$^', $_POST['txtPostalCode']) && $_POST['txtPostalCode'] != "")
{
$_SESSION['msg'] .= "Warning invalide Postal Code";
}
then the code goes on to display $_SESSION['msg'].
The problem is that whatever I enter in $_POST['txtPostalCode'] it NEVER get parse by the REGEX.
You made the entire capturing group optional:
^([A-Z][0-9][A-Z][0-9][A-Z][0-9])?$^
^
It's also not a good idea to use regex metadata characters as your delimiter. Try this regex, which matches an uppercase letter and a number three times:
/^((?:[A-Z][0-9]){3})$/
You don't need to make the capturing group optional because you handle the logic for when the user doesn't submit a code with the && $_POST['txtPostalCode'] != "" part of the if statement.
Finally, since you're not even using the matches from this regex, you don't need the capturing group:
/^(?:[A-Z][0-9]){3}$/
Your regex will match invalid postal codes.
A quick Google search for "canadian postal code regex" bought up
^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$
You may also want to put your $_POST['txtPostalCode'] != "" condition first since there's no point in executing a regex if the value is empty to begin with.
Edit: As pointed out by the comments, the quantifiers are redundant:
^[ABCEGHJKLMNPRSTVXY]\d[A-Z] *\d[A-Z]\d$

Don't match if string contains specific text

I have made this regex:
(?<=span class="ope">)?[a-z0-9]+?\.(pl|com|net\.pl|tk|org|org\.pl|eu)|$(?=<\/span>)$
It does match the strings like: example.pl, example12.com, something.eu but it will also match the dontwantthis.com.
My question is how to don't match a string in case if it contains the dontwantthis string?
You're probably following your regex with a loop to cycle through matches. In this case, it's probably easiest to just check for the presence of the dontwantthis substring and continue if it's there. Trying to implement it in regex is just asking for trouble.
It seems that you are extracting content from span elements using a regular expression. Now, despite all the reasons why this is not such a good idea...
... just keep the expression you have. Then, if you have a match, filter out the matched entries that should be rejected.
var $match = extractContentFromHtml($html); // use regex here, return false if no match
if ($match && validMatch($match)) {
// do something
}
where validMatch(string) should check if the value exists in some array, for example.

Space validation in full name field

I want to place check in Full name field that full name field should accept space between first and last name using i am using strrpos() function for it but not working
You could use a regex...
if (preg_match("/(.+)( )(.+)/", $full_name))
{
// returns true if name is formed of two words with a space between
}
For even better validation, you can use \w although keep in mind that it will only match English word characters. See here for more info: Why does \w match only English words in javascript regex?
preg_match("/(\w+)( )(\w+)/", $full_name)

regular expression to match emails

i am stuck at particular problem i have username field where on only alphabets numbers and . - and _ are allowed and should always start with alphabet
here are examples what are accepted
someone#mydomain.com
something1234#mydomain.com
someething.something#mydomain.com
something-something#mydomain.com
something_something#mydomain.com
something_1234#mydomain.com
something.123#mydomain.com
something-456#mydomain.com
what i have done till now is
[a-zA-Z0-9]+[._-]{1,1}[a-zA-Z0-9]+#mydomain.com
this matches all my requirement except of problem it dosent match
someone#mydomain.com
someont123#mydomain.com
but it even matches
someone_someone_something#mydomain.com
which is not required i am really not getting how to solve this one thing i tried is
[a-zA-Z0-9]+[._-]{0}[a-zA-Z0-9]+#mydomain.com
but this is also not solving my problem now it accepts everything like
something+455#mydomain.com
which is not required please help me
If you want to make the - or . optional, then you have to replace the {1,1} (quantifier: once) with an ? (quantifier: one or none) here:
[a-zA-Z0-9]+[._-]?[a-zA-Z0-9]+#mydomain.com
The reason this regex also matches shorter addresses without delimiter -._ is that you don't assert the whole string, but just some part of it. Use start ^ and end $ anchors:
^[a-zA-Z0-9]+[._-]?[a-zA-Z0-9]+#mydomain\.com$
This is why we have filter_var($email, FILTER_VALIDATE_EMAIL).
If email address is valid, then you just have to check if it ends with #domain.com. That could be done with strrpos($email, '#domain.com').

How to validate a regex with PHP

I want to be able to validate a user's inputted regex, to check if it's valid or not. First thing I found with PHP's filter_var with the FILTER_VALIDATE_REGEXP constant but that doesn't do what I want since it must pass a regex to the options but I'm not regex'ing against anything so basically it's just checking the regex validity.
But you get the idea, how do I validate a user's inputted regex (that matches against nothing).
Example of validating, in simple words:
$user_inputted_regex = $_POST['regex']; // e.g. /([a-z]+)\..*([0-9]{2})/i
if(is_valid_regex($user_inputted_regex))
{
// The regex was valid
}
else
{
// The regex was invalid
}
Examples of validation:
/[[0-9]/i // invalid
//(.*)/ // invalid
/(.*)-(.*)-(.*)/ // valid
/([a-z]+)-([0-9_]+)/i // valid
Here's an idea (demo):
function is_valid_regex($pattern)
{
return is_int(#preg_match($pattern, ''));
}
preg_match() returns the number of times pattern matches. That will be
either 0 times (no match) or 1 time because preg_match() will stop
searching after the first match.
preg_match() returns FALSE if an error occurred.
And to get the reason why the pattern isn't valid, use preg_last_error.
You would need to write your own function to validate a regex. You can validate it so far as to say whether it contains illegal characters or bad form, but there is no way to test that it is a working expression. For that you would need to create a solution.
But then you do realize there really is no such thing as an invalid regex. A regex is performance based. It either matches or it doesn't and that is dependent upon the subject of the test--even if the expression or its results are seemingly meaningless.
In other words, you can only test a regular expression for valid syntax...and that can be nearly anything!

Categories