fenfe1
fenfe1

Reputation: 71

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.

Upvotes: 0

Views: 196

Answers (2)

user1646111
user1646111

Reputation:

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

Upvotes: 2

phpisuber01
phpisuber01

Reputation: 7715

preg_match("/\@\d\d:\d\d/ims", "<input string>", $matches)

Use \ to escape special characters, the @ is a delimiter.

Upvotes: 0

Related Questions