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.
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"
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With