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';
Related
I am a Rubyist trying to implement some of my code in PHP and not able to get the equivalent PHP code for this particular def.Can anyone help me out.Thanks in advance.
def check_condition(str)
str =~ SOME_REGEX
end
In PHP it looks like:
function check_condition($str) {
return preg_match(SOME_REGEX, $str);
}
Unfortunately there is no regex-match operator in PHP unlike some other languages. You'll have to call a function. Follow the manual of preg_match() and the manual page about the so called perl compatible regular expresssions (preg) in general.
Something additional. After reading the manual page of preg_match you know that the method returns an integer, the number of matches found. As the method returns after the first match this can be only 0 or 1. As of the loose typing system of PHP this would be good for using it in loose comparisons like:
if(check_condition($str)) { ....
if(check_condition($str) == true) { ...
But it would not work in a strict comparison:
if(check_condition($str) === true) { ...
Therefore it would be a good idea to cast the return value of preg_match:
function check_condition($str) {
return (boolean) preg_match(SOME_REGEX, $str);
}
Update
I have thought a little bit about my last suggestion and I see a problem with this. preg_match() will return an integer if all is working fine but boolean FALSE if an error occurs. For example because of a syntax error in the regex pattern. Therefore you will be not aware of errors if you are just casting to boolean. I would use exceptions to show that an error was happening:
function check_condition($str) {
$ret = preg_match(SOME_REGEX, $str);
if($ret === FALSE) {
$error = error_get_last();
throw new Exception($error['message']);
}
return (boolean) $ret;
}
Have a look at preg_match:
if (preg_match('/regex/', $string) {
return 1;
}
Isn't it preg_match?
function check_condition($str) {
return preg_match(SOME_REGEX,$str);
}
I don't think there is an equivalent.
preg_match returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
=~however returns the position where the match starts, or nil if there is no match. Since nil is false and all numbers including zero are true, boolean operations are possible.
puts "abcdef" =~ /def/ #=> 3 # don't know how to get this from a RegExp in PHP
puts "Matches" if "abcdef"=~ /def/ #=> Matches
I have to loop through text files and return substrings found in the text that are either 8 or 9 characters long and contain the letter "k". Some examples of the substrings that must be found: 1998k1748, 1999k426, 2003k3429, 2012k325, etc. What would the regular expression be for this kind of search? I am using PHP.
Any help would be appreciated.
This is what I have after using Chirag's expression:
error_reporting(E_ALL);
shell_exec('D:\wamp\bin\xpdf\bin32\pdftotext.exe d.pdf x.txt');
$mypdf = file_get_contents("x.txt");
preg_match('\d{4}k\d{3,4}', $mypdf, $result);
echo $result[0];
But I get the following error: Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in D:\wamp\www\pdf2text.php on line 8
This regex will work if the string is always in the form of (4-digit-number)k(3-or-4-digit-number) as described by RedBaron:
\d{4}k\d{3,4}
How about an if else
if ((strlen($string) ==8 || strlen($string) ==9 ) && strpos($string, 'k') ) {
//do somethig
}
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);
}
My current regular expression should be correct, though I wouldn't expect so, it doesn't work properly. It won't return "Got Match"
My currrent code is as follows:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("^http://steamcommunity\.com/id/.*?\n$", $id)) {
print "Got match!\n";
}
You're missing delimiters on your regex:
if (preg_match("#^http://steamcommunity\.com/id/.*?\n$#", $id)) {
^--here ^--here
Note that I've used # as the delimiter here, since that saves you having to escape all of the internal / charrs, if you'd used the traditional / as the delimiter.
You need a delimiter, like this:
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
^ ^
And what's with the newline at the end? Surely you don't need that.
You're missing delimiters. For example:
"#^http://steamcommunity\.com/id/.*?\n$#"
Also, you're trying to match a newline (\n) that isn't in your string.
You need to add the pattern delimiter:
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?(\n|$)#", $id)) {
print "Got match!\n";
}
There are a couple of things that are wrong with it. First of all, you need to delimit the start and end of your regex with a character. I used #. You're also matching for a new line at the end of your regex, which you don't have and likely won't ever have in your string.
<?php
$id = "http://steamcommunity.com/id/TestID";
if (preg_match("#^http://steamcommunity\.com/id/.*?$#", $id)) {
print "Got match!\n";
}
?>
http://codepad.viper-7.com/L7XctT
First of all, your regex shouldn't even compile because it's missing delimiters.
if (preg_match("~^http://steamcommunity\.com/id/.*?\n$~", $id)) {
^---- these guys here -----^
Second of all, why do you have a \n if your string doesn't contain a new line?
And finally, why are you using regex at all? Effectively, you are just trying to match a constant string. This should be equivalent to what you are trying to match:
if (strpos($id, 'http://steamcommunity.com/id/') === 0) {
You need to have starting and ending delimiter in your pattern like /pattern/ or #pattern# or with brackets (pattern). Why is that? To have some pattern modifiers after ending delimiter like #pattern#i (ignore case)
preg_match('(^http://steamcommunity\.com/id/.*?\n$)', $id)
As the say your patten is start and end wrong. (Delimiter)
But this will be a better match of a 64-bit Steam ID. (Minimum 17 and Maximum 25 numbers)
if( preg_match("#^http://steamcommunity\.com/id/([0-9]{17,25})#i", $id, $matches) )
{
echo "Got match! - ".$matches;
}
I believe that there is no need for you to require that the string must end with a line break.
Explanation.
http://steamcommunity\.com/id/([0-9]{17,25})
^--- string ---^^-- Regexp --^
[0-9] - Match a number between 0 to 9
{17,25} - Make 17 to 25 matches
() - Returns match
Or use pattern as those (It is the same):
/^http:\/\/steamcommunity\.com\/id\/([0-9]{17,25})/i
(^http://steamcommunity\.com/id/([0-9]{17,25}))i
Regular Expressions PHP Tutorial
Online regular expression testing <- Dont use delimiter.
<?php
# URL that generated this code:
# http://txt2re.com/index-php.php3?s=http://steamcommunity.com/id&-1
$txt='http://steamcommunity.com/id';
$re1='(http:\\/\\/steamcommunity\\.com\\/id)'; # HTTP URL 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$httpurl1=$matches[1][0];
print "($httpurl1) \n";
}
#-----
# Paste the code into a new php file. Then in Unix:
# $ php x.php
#-----
?>
Resorces:
http://txt2re.com/index.php3?s=http://steamcommunity.com/id&-1
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.