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

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

WBOY
Release: 2023-03-02 09:38:01
Original
1236 people have browsed it

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

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

回复内容:

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

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

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

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

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

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template