preg_match(): Unknown modifier 'h' in php - php

This error is shown when trying to match an array of words to a user typed text..
foreach($items as $k=>$item){
if($item!='' && preg_match("/".$item."/", $opText)){
if(!in_array($item,$params[$val['name']],true)){
$params[$val['name']][]=$item;
}
}
}

$item has a / in it, which means that it thinks that the regex ends sooner than it does.
/goldfish/herring/
// ^ Not actually a modifier (h) - just an unescaped string
You can use the preg_quote($string, '/') function for this to turn it into the following:
/goldfish\/herring/
// ^ Escaped
Usage:
foreach($items as $k=>$item){
if($item!='' && preg_match("/".preg_quote($item,"/")."/", $opText)){
if(!in_array($item,$params[$val['name']],true)){
$params[$val['name']][]=$item;
}
}
}
Tip:
If this is a hardcoded regex, you can change your escape character to make the regex easier to read by not having to escape a commonly used character:
~goldfish/herring~
// ^ ^
// | \- Using a different modifier
// |
// \- Different from the modifier, so we don't have to escape it

If you have dynamic input, it would be wise to use preg_quote() to be sure that this input doesn't violate any regular expression rules.
foreach($items as $k=>$item){
if($item!='' && preg_match("/".preg_quote($item, '/')."/", $opText)){
if(!in_array($item,$params[$val['name']],true)){
$params[$val['name']][]=$item;
}
}
}

You need preg_quote():
preg_match("/".preg_quote($item)."/", $opText)

Related

regex \p{L} problems

im using this for my Validation:
$space = "[:blank:]";
$number = "0-9";
$letter = "\p{L}";
$specialchar = "-_.:!='\/&*%+,()";
...
$default = "/^[".$space.$number.$letter.$specialchar."]*$/";
if (!preg_match($all, $input)){
$error = true;
}
The Problem i have is:
all is working except "ü"... "Ü" is but "ü" not and i dont know why?
\p{L} should accept all letters and special letters... i dont get it why its not working :(
anyone an idea what i can do?
The data i try to validate is a POST Value from a registration FORM
// p.s. if im using \p{L}ü i get an error like this:
Compilation failed: range out of order in character class at offset 23 in...
Escape the dash:
$specialchar = "\-_.:!='\/&*%+,()";
# here __^
Also add the /u modifier for unicode matching:
$default = "/^[".$space.$number.$letter.$specialchar_def."]*$/u";
# here __^
Test:
$space = "[:blank:]";
$number = "0-9";
$letter = "\p{L}";
$specialchar = "\-_.:!='\/&*%+,()";
$default = "/^[".$space.$number.$letter.$specialchar."]*$/u";
// wrong variable name ^^^^^^^^^^^^ in your example.
$input = 'üÜ is but ';
if (!preg_match($default, $input)){
echo "KO\n";
} else {
echo "OK\n";
}
Output:
OK
The problem is the position that the hyphen is placed in. Within a character class you can place a hyphen as the first or last character in the range. If you place the hyphen anywhere else you need to escape it in order to add it to your class.
$specialchar = "_.:!='\/&*%+,()-";
Also you need to add the u (Unicode) modifier to your regular expression. This modifier turns on additional functionality of PCRE and pattern strings are treated as (UTF-8) and you have the wrong variable in the pattern.
$default = "/^[".$space.$number.$letter.$specialchar."]*$/u";
The - is a special character in character class used to specify a range of character. When you construct the regex by string concatenation, it is recommended that you escape it \-.
Including the fix above, there is another problem in "\-_.:!='\/&*%+,()". Do you want to include \ and /? Or only one of them?
If you want to include both, you should specify it as "\-_.:!='\\\\\/&*%+,()".
If you don't want to escape /, you can replace your separator / in the construction of $default to something not used in your regex, for example ~. In that case, the list of special character will have one less \: "\-_.:!='\\\\/&*%+,()".

Escaping # symbol in regular expression using preg_match

I am building an application that processes some transactions with descriptions such as:
cash bnkm aug09 : bt phone / a#19:10
I need to extract the time from such strings using a regular expression using preg_match.
I have written a regex that works on this website:
http://www.switchplane.com/awesome/preg-match-regular-expression-tester?pattern=%2F%40%5Cd%5Cd.%5Cd%5Cd%2F&subject=cash+bnkm++++aug09+%3A+bt+phone+%2F+a%4019%3A10
But not in my code, as a, Warning: preg_match(): Unknown modifier '#' error is given.
The regex I am using is: /#\d\d.\d\d/ and the call to preg_match is as below:
$matches = array();
if (preg_match('/'.'/#\d\d.\d\d/'.'/', 'cash bnkm aug09 : bt phone / a#19:10', $matches) === 1) {
//Carry out trigger
echo 'yes';
} else {
echo 'no';
}
Essentially it seems to choke on the # symbol - which I can't seem to escape.
I am quite new to regular expressions but can't find any description of # being used for as a special character so would have assumed it would be used to test the string rather than alter how the string was tested.
Any help on how to fix this would be appreciated.
try this:
if (preg_match('/#\d\d:\d\d/', 'cash bnkm aug09 : bt phone / a#19:10', $matches) === 1) {
//Carry out trigger
echo 'yes';
print_r($matches);//Array ( [0] => #19:10 )
} else {
echo 'no';
}
in your pattern there are two extra slashes:
'/'.'/#\d\d.\d\d/'.'/'
^-- ^--
If # not used as delimiter, then no need to escape it
preg_match("/\#\d\d:\d\d/ims", "<input string>", $matches)
Use \ to escape special characters, the # is a delimiter.

Unknown modifier in regular expression [duplicate]

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);
}

PHP Regular Expression Failing

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

PHP: preg_match

i need to write a case which only except the a-zA-Z0-9 characters with underscore and white space(1 or more than 1) and ignore all rest of the characters.I wrote a code but its not working properly.
In those case should be wrong but its show OK
1) test msg#
2) test#msg
3) test!msg
also those should be OK but currently shows wrong.
1) test msg.-(Two white space)
what i should to change in my code .pls help and see my code below.
$message=$_GET['msg'];
if(preg_match('/[^A-Za-z0-9]\W/',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}
Here's an optimized version of the one left by riad:
$message = $_GET['msg'];
if ( preg_match('/^[a-z0-9_ ]+$/i', $message) )
{
echo 'Ok';
}
else
{
echo 'Wrong';
}
I've removed the A-Z (uppercase) from the regular expression since the i modifier is used.
I'd also like to explain what you did wrong in the example you provided.
First, by putting the ^ inside the square brackets ([]), you're essentially doing the opposite of what you were trying to do. Place a ^ inside the square brackets means "not including."
You were missing a *, + or ? at the end of the square bracket, unless you only wanted to match a single character. The * character means 0 or more, + means 1 or more and ? means 0 or 1.
The \W means any non-word character. That's probably not what you wanted.
Finally, to starting a regular expression with ^ means that the beginning of the string you're string to match must start with whatever is after the ^. Ending the regular expression with a $ means that the string must end with the characters preceding the $.
So by typing /^[a-z0-9_ ]+$/i you're saying match a string that starts with a-z0-9_ or a space, that contains at least of those characters (+) and ends.
PHP has a lot of documentation of the PCRE regular syntax which you can find here: http://ca2.php.net/manual/en/reference.pcre.pattern.syntax.php.
$message=$_GET['msg'];
if(preg_match('/^[a-zA-Z0-9_ ]+$/i',$message))
{
echo "Wrong";
}
else
{
echo "OK";
}

Categories