php 从字符串中删除特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19521758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:38:22  来源:igfitidea点击:

Removing special Characters from string

phpregexstringpreg-replacespecial-characters

提问by user2092317

I am using a function for removing special character from strings.

我正在使用从字符串中删除特殊字符的函数。

function clean($string) {
   $string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

And here is the test case

这是测试用例

echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g

with Reference from SO Answer. The problem is what if ' is the last character in my string , Like I get a string America'from a excel file ,If I put that in this function, it wouldn't escape '.Any help when first and last character is '

参考来自 SO Answer。问题是如果 ' 是我的字符串中的最后一个字符,就像我America'从 excel 文件中获取一个字符串一样,如果我把它放在这个函数中,它就不会转义'。当第一个和最后一个字符是时,任何帮助'

回答by user2092317

try to replace the regular expectation change

尝试替换常规的期望变化

preg_replace('/[^A-Za-z0-9\-]/', '', $string);

with

preg_replace("/[^A-Za-z0-9\-\']/", '', $string);  // escape apostraphe

or

或者

you can str_replaceIt is quicker and easier than preg_replace()Because it does not use regular expressions.

你可以str_replace它比preg_replace()更快更容易, 因为它不使用正则表达式。

$text = str_replace("'", '', $string);

回答by Aditya P Bhatt

In a more detailed manner from Above example, Considering below is your string:

从上面的例子中以更详细的方式,考虑下面是你的字符串:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! ??? ?? ????? ??????! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text ?? ???? test 123 ?,.m,............ ~~~ ??]??}~?]?}"; ';

Code:

代码:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows:English letters (Capital and small), 0 to 9 and characters !@#$%^&*().

Allows:英文字母(大小写)、0到9和字符 !@#$%^&*().

Removes:All html tags, and special characters other than above

Removes:所有 html 标签,以及上述以外的特殊字符

回答by user2864030

At a first glance i think that the addslashes function could be a starting point. http://php.net/manual/en/function.addslashes.php

乍一看,我认为 addlashes 函数可能是一个起点。http://php.net/manual/en/function.addslashes.php

回答by AbraCadaver

Definitely a better pattern out there, but this should work for the entire string:

绝对是一个更好的模式,但这应该适用于整个字符串:

preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", '', $string);

If you need to replace them around words in the string you'll have to use \b for word boundaries. Also, if you want to replace multiples at the start or end you'll need to add a + to those.

如果您需要在字符串中的单词周围替换它们,则必须使用 \b 作为单词边界。此外,如果您想在开头或结尾替换倍数,则需要在其中添加一个 +。