开发者

PHP regex periods

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 wor开发者_如何学编程k.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜