How do I make use of postcode regex in PHP? [duplicate] - php

I'm using this validator:
//validate postcode
function IsPostcode($postcode)
{
$postcode = strtoupper(str_replace(' ','',$postcode));
if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
{
return true;
}
else
{
return false;
}
}
From this link.
But I want to be able to validate postcodes like ME20 and TN10 instead of a full blown ME20 4RN, TN0 4RN. This is the part of the postcode known as the 'outward code'.
Can someone help me out with the regex?

you can use my updated regex to solve you problem
it working from my end to validate UK zip code
<?php
function IsPostcode($postcode)
{
$postcode = strtoupper(str_replace(' ','',$postcode));
if(preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]?[\s]?[0-9][ABD-HJLNP-UW-Z]{2}$)/i",$postcode) || preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]$)/i",$postcode))
{
return true;
}
else
{
return false;
}
}
echo $result = IsPostcode('ME20');
?>
OUTPUT
1
Hope this will sure help you.

Related

Preg allowing Blank records

I have the below code for matching an email address using regular expression rules.
It works well, but I've recently noticed that it seems to match a "Blank" email address.
if (preg_match("/.* <.*#.*\..*>/i",$this->to,$matches)) {
$this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);
} else {
$this->email_to = $this->to;
}
My understanding of the preg_match is:-
Looks for any character, except a line break
< anycharacter#anything.anything >
Case-insensitive?
Following those rules, I can't quite work out why it matches a blank / no email address if someone can give some guidance.
Thank you.
No needs for preg_match + preg_replace.
if (empty($this->to)) {
$this->email_to = 'Is empty'; # assign what you want
} elseif (preg_match("/<(.+?#.+?\..+?)>/", $this->to, $matches)) {
$this->email_to = $matches[1];
} else {
$this->email_to = $this->to;
}
I don't know why it behaves like that but an easy solution is to ask if the string is blank
if (preg_match("/.* <.*#.*\..*>/i",$this->to,$matches)) {
if ($matches != ""){
$this->email_to = preg_replace("/.*<(.*)>.*/","$1",$this->to);
} else { $this->email_to = $this->to; }
} else {
$this->email_to = $this->to;
}

How to write preg_match for price

I need a function which check string which is basically price of an item. And it must be like 1-5 characters,2 characters.
Example:
99,99€ == GOOD
99,9€ == BAD
999999,99€ == BAD
Regards!
if (preg_match("~^\\d{1,5}+(:\\,\\d{1,2})$~", $number)) {
return true;
} else {
return false;
}
This will work best for price.
Don't forget you must not allow prices starting with more than one 0 like 000,99 or 0999,99
if(preg_match('/^(?:0|[1-9]\d*)(?:\,\d{2})?$/', $number))
{
return true;
}
else
{
return false;
}
Try this....
<?php
$regex = '/^[\d]{1,5},[\d]{2}$/';
$price = '12321,12';
var_dump( preg_match($regex, $price) );

php: validate if field starts with certain character

I'm using the Contact Form 7 plugin on wordpress to collect data inputted in the fields, I'm now looking to set up some validation rules using this neat extension: http://code-tricks.com/contact-form-7-custom-validation-in-wordpress/
What I'm after is to only allow one word only in the text field (i.e. no whitespace) and this one word has to begin with the letter 'r' (not case sensitive).
I've written the no white space rule as follows:
//whitespace
if($name == 'WhiteSpace') {
$WhiteSpace = $_POST['WhiteSpace'];
if($WhiteSpace != '') {
if (!preg_match('/\s/',$WhiteSpace)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
Is it possible to incorporate the second rule into this also? So no whitespace, and the word must begin with the letter 'r'? Any suggestions would be greatly appreciated!
EDIT:
seems core1024 answer does work, but only one of them:
//FirstField
if($name == 'FirstField') {
$FirstField = $_POST['FirstField'];
if($FirstField != '') {
if (!preg_match("/(^[^a]|\s)/i",$FirstField)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
//__________________________________________________________________________________________________
//SecondField
if($name == 'SecondField') {
$SecondField = $_POST['SecondField'];
if($SecondField != '') {
if (!preg_match("/(^[^r]|\s)/i", $SecondField)) {
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Invalid Entry.';
}
}
}
I want to use this code twice, once to validate the first character being a on one field the second instance with the first character being r on another field. But it only seems the SecondField validation rule is working.
Try to use:
preg_match('/^r[^\s]*$/i',$WhiteSpace)
instead of:
!preg_match('/\s/',$WhiteSpace)
You need this:
if (!preg_match("/(^[^r]|\s)/i", $WhiteSpace)) {
It matches any string that doesn't start with r/R or contain space.
Here's a test:
$test = array(
'sad',
'rad',
'ra d'
);
foreach($test as $str) {
echo '"'.$str.'" -> '.preg_match('/(^[^r]|\s)/i', $str).'<br>';
}
And the result:
"sad" -> 1
"rad" -> 0
"ra d" -> 1

regex for currency (euro)

i am trying this code for make a validation for a value. (regex from this site)
UPDATE:
Now i have
$value1=250;
$value2=10000;
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary']) || (!$form['salary'])>$value1."€" && (!$form['salary'])<$value2."€" ){
echo ("invalido");
return false;
}
else
echo ("valido");
return true;
the code works well, but 20€ is accepted, so the problem now is not the regex, but compare values like 200€ or 1000€.
this probably is wrong
(!$form['salary'])>$value1."€"
example some Input values:
200€
200
200.5
200.50€
limits - 250€ to 10000€
thanks
This code below solved my problem:
if (!preg_match("/^(([^0]{1})([0-9])*|(0{1}))(\,\d{2}){0,1}€?$/", $form['salary'])) {
echo "invalid";
return false;
} else {
$value1 = 400;
$value2 = 10000;
$salary = $form['salary'];
$salary = preg_replace('/[€]/i', '', $salary);
if($salary < $value1 || $salary > $value2) {
echo "bad values";
return false;
} else {
echo "valid";
return true;
}
}
The regex solution would look like this
^(?:10000|(?:(?:(?:2[5-9]\d)|[3-9]\d{2}|\d{4})(?:[,.]\d{2})?))€?$
See here online on Regexr
But it would be better for checking if a value belongs to a range, not to use a regex. You can extract the value easily and do a normal <> check on numbers outside.
My contribution. It works great.
final Pattern pattern = Pattern.compile("^([0-9]+)|((([1-9][0-9]*)|([0-9]))([.,])[0-9]{1,2})$");

Why wont my email validation work? PHP

I have used
if (!preg_match('/[a-z||0-9]#[a-z||0-9].[a-z]/', $email)) {
[PRINT ERROR]
}
&
if (!eregi( "^[0-9]+$", $email)) {
[PRINT ERROR]
}
&
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
[PRINT ERROR]
}
I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..
I am using PHP
Try
'/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/'
...
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
[PRINT ERROR]
}
As far as I can see, none of your regex expressions would match an email.
Try this from the Kohana source code:
function email($email)
{
return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+#(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string) $email);
}
Check your php version. eregi is deprecated after 5.3.0. Also, the regex is not correct.
Try this (from wordpress):
// from wordpress code: wp-includes/formatting.php
function is_email($user_email)
{
$chars = "/^([a-z0-9+_]|\\-|\\.)+#(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (strpos($user_email, '#') !== false && strpos($user_email, '.') !== false)
{
if (preg_match($chars, $user_email)) {
return true;
} else {
return false;
}
} else {
return false;
}
}

Categories