Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex periods

Tags:

regex

php

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.

like image 802
TOKYOTRIBE4EVAR Avatar asked Oct 25 '10 06:10

TOKYOTRIBE4EVAR


2 Answers

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".

like image 133
Gumbo Avatar answered Sep 30 '22 02:09

Gumbo


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.

like image 38
jensgram Avatar answered Sep 30 '22 02:09

jensgram