TOKYOTRIBE4EVAR
TOKYOTRIBE4EVAR

Reputation: 51

Escaping metacharacters with a single backslash in a double quote wrapped regex string returns no matches

How do I put a period into a PHP regular expression?

The way it is used in the code is:

echo(preg_match("/\$\d{1,}\./", '$645.', $matches));

But apparently the period in that $645. doesn't get recognized. Requesting tips on how to make this work.

Upvotes: 5

Views: 10647

Answers (2)

jensgram
jensgram

Reputation: 31508

Escape it. The period has a special meaning within a regular expression in that it represents any character — it's a wildcard. To represent and match a literal . it needs to be escaped which is done via the backslash \, i.e., \.

/[0-9]\.[ab]/

Matches a digit, a period, and "a" or "ab", whereas

/[0-9].[ab]/

Matches a digit, any single character1, and "a" or "ab".

Be aware that PHP uses the backslash as an escape character in double-quoted string, too. In these cases you'll need to doubly escape:

$single = '\.';
$double = "\\.";

UPDATE
This echo(preg_match("/\$\d{1,}./", '$645.', $matches)); could be rewritten as echo(preg_match('/\$\d{1,}\./', '$645.', $matches)); or echo(preg_match("/\\$\\d{1,}\\./", '$645.', $matches));. They both work.


1) Not linefeeds, unless configured via the s modifier.

Upvotes: 3

Gumbo
Gumbo

Reputation: 655169

Since . is a special character, you need to escape it to have it literally, so \..

Remember to also escape the escape character if you want to use it in a string. So if you want to write the regular expression foo\.bar in a string declaration, it needs to be "foo\\.bar".

Upvotes: 9

Related Questions