Home  >  Article  >  Backend Development  >  PHP regular escapes the $ symbol, but a slash doesn't work?

PHP regular escapes the $ symbol, but a slash doesn't work?

WBOY
WBOYOriginal
2016-12-01 01:27:171178browse

<code>$pattern = "/\{\$/";
preg_match($pattern, $this->content, $matches);
var_dump($matches)</code>

没有匹配到
但是改成两斜杠就管用了

回复内容:

<code>$pattern = "/\{\$/";
preg_match($pattern, $this->content, $matches);
var_dump($matches)</code>

没有匹配到
但是改成两斜杠就管用了

因为PHP里双引号内会解析变量,所以换成单引号,或再加个\即可。

<code>$pattern = "/\{\$var/";    // $var变量  
$pattern = '/\{\$/';</code>

在字符串里\本身就用为转义字符,所以在字符串里表示\需要使用\\。所以在对应$时,其实需要进行两次转意,也就是需要\\$

字符串中的单个\ 是不能被正确识别的 需要\\
有明大大 已经说得很详细了
$pattern = "/\\{\\$/";

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn