Escaping # symbol in regular expression using preg_match - php

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.

Related

preg_match(): Unknown modifier 'h' in 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)

PHP - Regex for a string of special characters

Morning SO. I'm trying to determine whether or not a string contains a list of specific characters.
I know i should be using preg_match for this, but my regex knowledge is woeful and i have been unable to glean any information from other posts around this site. Since most of them just want to limit strings to a-z, A-Z and 0-9. But i do want some special characters to be allowed, for example: ! # £ and others not in the below string.
Characters to be matched on: # $ % ^ & * ( ) + = - [ ] \ ' ; , . / { } | \ " : < > ? ~
private function containsIllegalChars($string)
{
return preg_match([REGEX_STRING_HERE], $string);
}
I originally wrote the matching in Javascript, which just looped through each letter in the string and then looped through every character in another string until it found a match. Looking back, i can't believe i even attempted to use such an archaic method. With the advent of json (and a rewrite of the application!), i'm switching the match to php, to return an error message via json.
I was hoping a regex guru could assist with converting the above string to a regex string, but any feedback would be appreciated!
Regexp for a "list of disallowed character" is not mandatory.
You may have a look at strpbrk. It should do the job you need.
Here's an example of usage
$tests = array(
"Hello I should be allowed",
"Aw! I'm not allowed",
"Geez [another] one",
"=)",
"<WH4T4NXSS474K>"
);
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";
foreach ($tests as $test) {
echo $test;
echo ' => ';
echo (false === strpbrk($test, $illegal)) ? 'Allowed' : "Disallowed";
echo PHP_EOL;
}
http://codepad.org/yaJJsOpT
return preg_match('/[#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/', $string);
$pattern = preg_quote('#$%^&*()+=-[]\';,./{}|\":<>?~', '#');
var_dump(preg_match("#[{$pattern}]#", 'hello world')); // false
var_dump(preg_match("#[{$pattern}]#", 'he||o wor|d')); // true
var_dump(preg_match("#[{$pattern}]#", '$uper duper')); // true
Likely, you can cache the $pattern, depending on your implementation.
(Though looking outside of regular expressions, you're best of with strpbrk as mentioned here too)
I think what you're looking for can be greatly simplified by including the characters that you want to allow like so:
preg_match('/[^\w!#£]/', $string)
Here's a quick breakdown of what's happening:
[^] = not included
\w = letters and numbers
! # £ = the list of characters you would also like to allow

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