php中如何去除标点符号
如何删除除这些字符之外的标点符号 .
=
$
'
-
<代码>€ <代码>%
How can I strip punctuation except for these characters .
=
$
'
-
€
%
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个巧妙的方法:
Here's a neat way to do it:
由于您需要匹配一些 Unicode 字符 (
€
),因此使用正则表达式是明智的。模式\p{P}
匹配任何已知的标点符号,并且断言将您想要的特殊字符排除在外,以免消失:Since you need to match some Unicode characters (
€
) it would be sensible to use a regular expression. The pattern\p{P}
matches any known punctuation, and the assertion excludes your desired special characters from vanishing:此处演示
,或者当然更短:
来源自
str_replace
手册的第一个示例Demo here
or, of course, shorter :
Source from 1st example of
str_replace
manual尽管指定要删除的字符会更正确且更容易,而不是指定您不想删除的字符(来自未知的集合)。
although it would be more correct and easy to specify the characters you want to strip, instead of characters (from an unknown set) you don't want to strip.
尝试:
你没有提到是否需要空格,所以这也会删除它。
Try:
You didn't mentioned if you wanted spaces or not, so that will strip that too.
问题:
需要将字符串保存为具有特定标点符号的 alphaNum,并且不想完全丢弃具有特殊标点符号的字符。
解决方案:
示例:
去掉所有标点符号:
ClassName::alpaNum($string);
删除所有标点符号,但转换特殊字符:
ClassName::alphaNum($string, null, true);
Alpha Num + 附加标点符号:
ClassName::alphaNum($string, array('_', '-', ',', '.'));
Alpha Num + 附加标点符号并转换:
ClassName::alphaNum($string, array('_', '-', ',', '.'), true);
结论:
如果您需要特殊字符并且不想完全丢弃它们,您可以在检查 alphaNum 之前转换它们。
(例如,关于清理文件名等)
如果丢弃特殊字符不会产生任何实际影响,并且系统并不真正期望这样做,您可以在不转换标点符号的情况下调用它,以节省处理能力。
(例如,在从字符串为大型数组设置键时)
我从这里得到了 cleanChars var:
(我稍微修改了一下)
https://github.com/vanillaforums/Garden/blob /master/library/core/class.format.php
The problem:
Need to save string as alphaNum with specific punctuation and don't want to completely discard characters with special punctuation.
The solution:
Examples:
Strip all punctuation:
ClassName::alpaNum($string);
Strip all punctuation but convert special chars:
ClassName::alphaNum($string, null, true);
Alpha Num + additional punctuation:
ClassName::alphaNum($string, array('_', '-', ',', '.'));
Alpha Num + additional punctuation and convert:
ClassName::alphaNum($string, array('_', '-', ',', '.'), true);
Conclusion:
If you are expecting special chars and don't completely want to discard them you can convert them before checking alphaNum.
(eg. on sanitizing file names etc.)
If discarding the special chars does not have any real impact and is not really expected on the system you can call it without conversion of punctuation to save processing power.
(eg. on setting keys for large arrays from strings)
I got the cleanChars var from here:
(I slightly modified it)
https://github.com/vanillaforums/Garden/blob/master/library/core/class.format.php