简体   繁体   English

PHP正则表达式期间

[英]PHP regex periods

How do I put a period into a PHP regular expression? 如何将句点放入PHP正则表达式?

The way it is used in the code is: 它在代码中的使用方式是:

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

But apparently the period in that $645. 但显然这段时间在$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" . 因此,如果要在字符串声明中编写正则表达式foo\\.bar ,则需要将其设置为"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 \\ , ie, \\. 它需要通过反斜杠\\来进行转义,即\\.

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

Matches a digit, a period, and "a" or "ab", whereas 匹配数字,句点和“a”或“ab”,而

/[0-9].[ab]/

Matches a digit, any single character 1 , and "a" or "ab". 匹配数字,任何单个字符1和“a”或“ab”。

Be aware that PHP uses the backslash as an escape character in double-quoted string, too. 请注意,PHP也使用反斜杠作为双引号字符串中的转义字符。 In these cases you'll need to doubly escape: 在这些情况下,你需要双倍逃避:

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

UPDATE UPDATE
This echo(preg_match("/\\$\\d{1,}./", '$645.', $matches)); 这个echo(preg_match("/\\$\\d{1,}./", '$645.', $matches)); could be rewritten as echo(preg_match('/\\$\\d{1,}\\./', '$645.', $matches)); 可以重写为echo(preg_match('/\\$\\d{1,}\\./', '$645.', $matches)); or echo(preg_match("/\\\\$\\\\d{1,}\\\\./", '$645.', $matches)); echo(preg_match("/\\\\$\\\\d{1,}\\\\./", '$645.', $matches)); . They both work . 他们 工作


1) Not linefeeds, unless configured via the s modifier. 1)不是换行符,除非通过s修饰符配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM