简体   繁体   中英

Escaping characters in regular expressions in PHP

The following returns true:

$bool1 = preg_match("/5/", "Your bill is $5.00 dude");
var_dump($bool1);

I expect this because '5' is in the string.But the following returns false:

$bool1 = preg_match("/\$5\./", "Your bill is $5.00 dude");
var_dump($bool1);

I thought I was escaping the $ correctly so that it would look for $5 in the string and find it, but no. Can someone explain? Thanks.

使用单引号来防止PHP误解任何转义:

$bool1 = preg_match('/\$5\./', "Your bill is $5.00 dude"); 

你应该使用preg_quote()函数进行正确的转义

$bool1 = preg_match('/\$5\./', "Your bill is $5.00 dude");
var_dump($bool1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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