简体   繁体   English

正则表达式-preg_replace字符串

[英]regex - preg_replace string

i want to replace a string's non-alphanumeric characters into space. 我想将字符串的非字母数字字符替换为空格。

i used $title= preg_replace("/[^a-zA-Z0-9\\s]/", " ", $title); 我用$title= preg_replace("/[^a-zA-Z0-9\\s]/", " ", $title);

so when users inputs 所以当用户输入

abc!?d$ ABC!?d $

it will be 这将是

abc d A B C D

but beacuse user input it to a text-input it goes to "x.php?title=abc!?d$". 但由于用户将其输入到文本输入中,因此转到“ x.php?title = abc!?d $”。 i want it to go to "x.php?title=abc+d" because i want "abc d", "abc$$$$$$$$$d", "abc__.!d" etc. to go to same url. 我希望它转到“ x.php?title = abc + d”,因为我希望“ abc d”,“ abc $$$$$$$$$$ d”,“ abc __。!d”等转到相同的网址。 how can i manage this. 我该如何管理。 thank you. 谢谢。

Basically, what you're saying is that if there are more than one replacable characters next to each other, then you only want to put one space character there. 基本上,您要说的是,如果相邻的多个可替换字符彼此相邻,那么您只想在其中放置一个空格字符。 Is that right? 那正确吗?

In that case, yes, it's easy: you simply need to add a plus sign after the character class in the regex, like so: 在那种情况下,是的,这很容易:您只需要在正则表达式中的字符类之后添加一个加号,就像这样:

$title = preg_replace("/[^a-zA-Z0-9\s]+/", " ", $title);

The plus sign tells regex to look for one or more match of the preceding item. 加号告诉正则表达式查找前一项的一个或多个匹配项。

Hope that helps. 希望能有所帮助。

To get rid off unwanted characters use following code: 要摆脱不必要的字符,请使用以下代码:

$_GET['title'] = 'abc__.!d';

$title = preg_replace('/[^a-zA-Z0-9\s]+/', ' ', $_GET['title']); // "abc d"

Now, just redirect to correct URL (if needed) 现在,只需重定向到正确的URL(如果需要)

if ($_GET['title'] != $title) {
    header('Location: ....');
    die('Redirect to ...URL...');
}

Have you tried the \\W switch for matching non-aplha chars? 您是否尝试过\\W开关来匹配非aplha字符? (In conjunction with the + ) (与+结合使用)

$title= preg_replace(/\W+/g, " ", $title);

(In JavaScript you also need the /g flag as well, not sure if this is true for PHP) (在JavaScript中,您还需要/g标志,不确定PHP是否适用)

EDIT: 编辑:

The requirement states that all _ should be eliminated, so the following would work. 该要求指出,应消除所有_ ,因此下面的方法将起作用。

(\W|_)+

However, probably best to stipulate the exact chars you want in this instance, rather than trying to build up an exclude list, as my asnwer is starting to do. 但是,最好在这种情况下规定您想要的确切字符,而不是像我的请求开始那样尝试建立排除列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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