The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.
Any help would be much appreciated.
function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";
$phonevalid = 0;
if (ereg($phoneregexp, $phone))
{
$phonevalid = 1;
}else{
$phonevalid = 0;
}
}
Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg_match. I didn't get the warning.
Edit: after seeing the other comment, you meant "ereg" not "preg"... that gives the warning. Try using preg_match() instead ;)
<?php
function validate_phone($phone) {
$phoneregexp ='/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/';
$phonevalid = 0;
if (preg_match($phoneregexp, $phone)) {
$phonevalid = 1;
} else {
$phonevalid = 0;
}
}
validate_phone("123456");
?>
If this is PHP, then the regex must be enclosed in quotes. Furthermore, what's preg? Did you mean preg_match?
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
return preg_match($regex, $phone) !== 0;
EDIT: Or, using ereg:
return ereg($regex, $phone) !== FALSE;
(Here, the explicit test against FALSE isn't strictly necessary but since ereg returns a number upon success I feel safer coercing the value into a bool).
It's the [0-9\\- ] part of your RE - it's not escaping the "-" properly. Change it to [0-9 -] and you should be OK (a "-" at the last position in a character class is treated as literal, not part of a range specification).
Just to provide some reference material please read
Regular Expressions (Perl-Compatible)
preg_match()
or if you'd like to stick with the POSIX regexp:
Regular Expression (POSIX Extended)
ereg()
The correct sample code has already been given above.
Related
I have a couple of issues with this if statement which checks if a string ends with "address".
E.g this matches user_address, user_address1, user_address99, etc. Which is correct.
The problem is that it also matches user_address_location which is not correct.
I only want this to match if:
Is ends with _address
Also if it has a number on the end e.g _address2
/* Only establish an address field as ADDRESS if follows "user_address1" format */
if((stristr($column,"address") !== false)) {
$parts = explode("_", $column);
if (!empty($parts)) {
// address code
}
}
This might be a decent place to use a regex
if(preg_match('/^user_addesss\d*$/', $column) === 1){
}
Use regular expressions:
if(preg_match('/_address(\d+)?$/', $column))
{
}
if you are doing a lot of string comparing and manipulation this web application will be very useful to you: http://gskinner.com/RegExr/
It allows you to develop regular expressions against content with live feedback on matches and replacements.
You can make use of $ of regular expressions here. When using regular expressions $ specifies the end of a string
So, you can search for this regular expression:
$regexp = "^.*_address\d+$";
^ is the start, .* indicates any number of any characters _address is what you want to search for, \d+ says it can have numbers after address, and $ indicates end of string.
You can read more about regular expressions, and preg_match on php.net
change if((stristr($column,"address") !== false)) { to if(preg_match("/^user_address[0-9]*/", $column) == 1) {
I wanted to find a way to do it without regular expressions, sorry I should of made that clear in the question.
But I think I have found a way, not sure if it can be improved or performance compared to the regular expressions.
/* First establish it could be an address field e.g "user_address1" format */
$column_address = strpos($column, "_address");
if($column_address !== false) {
// remove everything before "_address"
$last = substr($column, $column_address);
// Check if "_address" OR remove "_address" and check if int
if($last == "_address" || intval(substr($last, 8))){
This question already has answers here:
Warning: preg_replace(): Unknown modifier
(3 answers)
Closed 3 years ago.
Does anyone knows why i receive this error : preg_match() [function.preg-match]: Unknown modifier '('
using this method:
function checkFBDateFormat($date) {
if(preg_match ("/^([0-9]{2})/([0-9]{2})/([0-9]{4})$/", $date, $parts)){
if(checkdate($parts[2],$parts[1],$parts[3]))
return true;
else
return false;
} else {
return false;
}
}
You did not escape your "/" and you didn't complete your if statements either, please try this:
function checkFBDateFormat($date) {
if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $date, $parts)){
if(checkdate($parts[2],$parts[1],$parts[3])) {
return true;
} else {
return false;
}
} else {
return false;
}
}
echo var_dump(checkFBDateFormat('08/09/2012'));
If the first char is e.g. an slash / is detected as delimiter fro the regular expression. Thus your regex is only the part ^([0-9]{2}). And everything after the second slash is recognized as modifiers for the regex.
If you really want to match a slash, use \/ to escape it
Since you are using slash in regular expression, need use other delimiter, try:
preg_match ("#^([0-9]{2})/([0-9]{2})/([0-9]{4})$#", $date, $parts)
You need to escape your slash, like so:
if(preg_match ("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $date, $parts)){
You use / as delimiter for your expression. However, it's completely unnecessary anyway
$parts = explode('/', $date);
Even better: http://php.net/datetime.createfromformat
To give you an idea what happens: PCRE regular expression require a delimiter at the start and the end of the pattern itself. Everything after the second delimiter is treated as modifier. Thus you decided to use / as delimiter (it's always the first character), so your pattern ended right after /^([0-9]{2})/. Everything next (which is a ( at first) is treated as modifier, but ( is not an existing modifier.
If you want to stay with regular expression, I recommend to use another delimiter like
~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~
#^([0-9]{2})/([0-9]{2})/([0-9]{4})$#
Just read the manual about the PCRE-extension
Two additional comments:
You should define $parts, before you use it
Remember, that the expression is quite inaccurate, because it allows dates like 33/44/5678, but denies 1/1/1970
You might want to consider not using regular expressions at all.
<?php
// simple example
$timestamp = strtotime('12/30/2012');
if ($timestamp) {
// valid dateā¦ Now do some magic
echo date('r', $timestamp);
}
This question already has answers here:
php validate integer
(7 answers)
Closed 9 years ago.
Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.
For example, any of the following values should be valid:
7
0
32
47534
The following SHOULD NOT be valid:
asdf
35/gdf
../34.
etc..
I'm using the following if statement to check for the positive integer value of "$original_stock".
if (preg_match("/^[0-9]$/", $original_stock))
{
$error .="Original stock must be numerical.";
}
Additionally, I have a price field which should be validated as either an int or a double.
If there's an easier alternative to using regex, that's okay too!
Thanks in advance :)
Try this regexp:
/^\d+$/
The issue with your existing regexp is that it only matches strings with exactly one digit.
As for validating an int or a double:
/^\d+\.?\d*$/
Note that that regexp requires that there be at least one digit.
Use:
/^[0-9]+$/
The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:
/^\d+$/
For floats, try something like:
/^\d+(\.\d{1,2})?/
This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)
To save yourself some headaches, you can also use the is_int and is_float functions.
Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:
if (!preg_match("/^\+$/", $original_stock)) {
// error
}
(note the !).
You may want to use the
is_int
Don't reinvent a wheel slower than an existing one, use a motorcycle: is_int.
#Assuming $original_stock is a single value...
if (is_int($original_stock)) {
#Valid, do stuff
}
else {
#Invalid, do stuff
}
#Assuming $original_stock is an array...
$valid = true;
foreach ($original_stock as $s) {
if (!is_int($s)) {
$valid = false;
break;
}
}
if ($valid) {...}
else {...}
I just ran into this exact problem and solved it this way using the regex.
I think the problem is your caret ^.
/^[0-9]$/
I moved it inside the class and got the results I needed.
function validate_int($subject)
{
//Pattern is numbers
//if it matches anything but numbers, we want a fail
$pattern = '/[^0-9]/';
$matches = preg_match($pattern, $subject);
if($matches > 0)
return false;
else
return true;
}
I was wondering if anybody knew if there was a way to concatenate a * (all) to a string inside an if (or switch) statement. For example if you had a URL called /hello/there and /hello/whats-up ... is there anyway you could have something like the following:
if ($url="/hello/" . *) {
sayHello();
} else { sayGoodebye(); }
etc... I don't think that's the correct syntax, but if anybody knows what I'm talking about it would be a great help.
Thanks (:
$match = "/hello/";
if (substr($url, 0, strlen($match)) === $match) {
sayHello();
} else {
sayGoodbye();
}
Do not use regular expressions if you don't have to...
You can also check for the position of $match in the $url string:
$match = "/hello/";
if (strpos($url, $match) === 0) {
sayHello();
} else {
sayGoodbye();
}
Use regular expressions:
http://www.regular-expressions.info/php.html
So it would be something like this:
if (ereg("/hello/", $url)) {
sayHello();
} else { sayGoodebye(); }
Although that would match anything with "/hello/" in it anywhere, so if you only wanted to match strings that start with "/hello/" you'd have to modify the expression. The point is, if you've never used regular expressions it's a good thing to invest some time into. It'll pay off eventually because at some point you're going to need this skill.
Edit: I'll leave my original code here as reference, but please see phihag's comments and use preg_match and the preg_match compatible expression instead of ereg and the expression I used.
I'm going through my code to replace any instances I'm using the ereg() function - which I was using for matching regex inside a string.
I could use a little direction, if someone has a better method than what I'm using.
Here's my old "currency validation" script:
function valid_currency($number){
if(ereg('^[0-9]+\.[0-9]{2}$', $number))
return true;
else
return false;
}
if(valid_currency(25.30)){
echo "valid currency";
}else{
echo "invalid currency string";
}
I replaced the ereg() with preg_match().
I'm getting this error now:
Warning: preg_match() [function.preg-match]: No ending delimiter '^'
I'm guessing the regular expression syntax isn't being recognized. From here I'm a little stuck.
preg requires delimiters around your regex. It can be almost anything though traditionally it's /. This should work:
preg_match('/^[0-9]+\.[0-9]{2}$/', $number)
You need the bounds for the regex statement, IE it's thinking you're starting the statement with ^ and saying there's no ending ^ indicating the end of the statement. Use /^[0-9]+\.[0-9]{2}$/ instead
in preg_match() or preg_match_all() uses "delimiters".examples:
/regEx/ or #regEx# or |regEx| or #regEx#.
I use: /regEx/
function valid_currency($n) {
return preg_match("/^\d+\.\d{2}$/", $n);
}
returns bool: 1(true) 0(false)
exmaple of use:
echo valid_currency("25.30") ? 'valid currency' : 'invalid currency string';