RegEx用于清理字符串(RegEx for cleanup a string)

编程入门 行业动态 更新时间:2024-10-20 20:53:34
RegEx用于清理字符串(RegEx for cleanup a string)

此RegEx用于从搜索表单中清除用户输入

$query = preg_replace("/[^A-Za-z0-9 _.,*&-]/", ' ', $query);

我需要将斜线添加为有效字符,但是如果我添加它,则会出现错误。 我认为我必须逃避它,但无法找到如何做到这一点

$query = preg_replace("/[^A-Za-z0-9 _.,*&-/]/", ' ', $query); // doesn't works $query = preg_replace("/[^A-Za-z0-9 _.,*&-//]/", ' ', $query); // doesn't works $query = preg_replace("/[^A-Za-z0-9 _.,*&-\/]/", ' ', $query); // doesn't works

使用PHP

This RegEx is for cleanup user input from a search form

$query = preg_replace("/[^A-Za-z0-9 _.,*&-]/", ' ', $query);

I need to add the slash as a valid character too, but if I add it, I get an error. I assume I have to escape it but can't find how to do that

$query = preg_replace("/[^A-Za-z0-9 _.,*&-/]/", ' ', $query); // doesn't works $query = preg_replace("/[^A-Za-z0-9 _.,*&-//]/", ' ', $query); // doesn't works $query = preg_replace("/[^A-Za-z0-9 _.,*&-\/]/", ' ', $query); // doesn't works

Using php

最满意答案

你可以使用其他的东西作为你的分隔符 - 尝试像这样:

$query = preg_replace("%[^A-Za-z0-9 _.,*&-/]%", ' ', $query);

在这种情况下,科比也发布了正确的逃避方法,但是当我将分隔符切换到表达式中没有使用的分隔符时,我发现正则表达式更具可读性。

编辑

一些额外的信息可以在http://www.php.net/manual/en/regexp.reference.delimiters.php找到(引用它在这里:)

“使用PCRE函数时,要求模式由分隔符包围。分隔符可以是任何非字母数字,非反斜杠,非空白字符。”

You can use something other then the / as your delimiter - try something like this:

$query = preg_replace("%[^A-Za-z0-9 _.,*&-/]%", ' ', $query);

Kobe also posted the correct way to escape in that situation, but I find the regex stays more readable when I switch the delimiter to something I'm not using in the expression, when possible.

EDIT

A bit of additional information can be found at http://www.php.net/manual/en/regexp.reference.delimiters.php (quoting it here:)

"When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character."

更多推荐

本文发布于:2023-08-05 03:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   RegEx   string   cleanup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!