如何使用'在单引号字符串中?

发布于 2024-12-29 09:22:31 字数 272 浏览 6 评论 0原文

我将以下内容用于 preg_replace

$replace = '/[!\/."",#\s\-:?"]+/';

例如,当我尝试在上面添加 ' 时,它会给我一个文件错误:

解析错误:语法错误,第 38 行 .../s.php 中出现意外的 T_NS_SEPARATOR

另外,是否有更简单的方法来列出所有要替换的符号?

I use the following for a preg_replace:

$replace = '/[!\/."",#\s\-:?"]+/';

For example when I try and add ' above it gives me an error on the file:

Parse error: syntax error, unexpected T_NS_SEPARATOR in .../s.php on line 38

Additionally, is there an easier way to list all of the symbols to be replaced?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吾性傲以野 2025-01-05 09:22:31

如果您想删除任何符号,请尝试:

$replace = "/[^a-zA-Z0-9 ]/";

^ 表示“除以下符号外的任何符号”。将您想要允许的任何字符添加到列表中。这比列出每个符号并处理转义要容易。

If you want to get rid of any symbol, try:

$replace = "/[^a-zA-Z0-9 ]/";

The ^ indicates "anything but the following". Add whatever characters you want to allow to the list. It's easier than listing every symbol and having to deal with escaping.

想你的星星会说话 2025-01-05 09:22:31

您需要对 ' 字符进行转义,因为它也是单引号字符串的分隔符:

$replace = '/[!\/.,#\s\-:?"\']+/';
                           ^^

通过在其前面添加 \ 来完成转义。这通常是合乎逻辑的,否则您将完成字符串定义,然后导致语法错误(PHP 无法解析您的代码)。请参阅 单引号字符串文档

是否有更简单的方法来列出所有要替换的符号?

仅仅列出它们是不是很容易(就像您已经做的那样)?所以我必须承认,我不清楚你真正关心的是什么,所以我无法提供更简单的东西。

You need to escape the ' character as it's also the delimiter of the single quoted string:

$replace = '/[!\/.,#\s\-:?"\']+/';
                           ^^

Escaping is done by adding \ in front of it. This is normally logical as you otherwise would have finished the string definition which then leads to a syntax error (PHP is not able to parse your code). See Single quoted String­Docs.

Is there an easier way to list all of the symbols to be replaced?

Isn't it easy enough to just list them (as you already do)? So I must admit it's not clear to me what you're actually concerned about so I can't offer something more easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文