如何删除前导和尾随的非字母数字字符

问题描述:

我希望从字符串中修剪"非字母数字,类似于 trim() 处理空格的方式.

I'm looking to "trim" non-alphanumerics from a string, similar to how trim() works with whitespace.

帮我把#str|ng# 转换成str|ng.

我可以删除尾随的非字母数字:

I can remove trailing non-alphanumerics with:

$string = preg_replace('/\W+$/', '', $string); // converts `#str|ng#` to `#str|ng`

并以:

$string = preg_replace('/^\W+/', '', $string); // converts `#str|ng#` to `str|ng#`

但我怎样才能同时完成这两项工作?

But how can I accomplish both at the same time?

尝试使用像这样的 ^\W+|\W+$ 模式:

Try using a ^\W+|\W+$ pattern like this:

$string = preg_replace('/^\W+|\W+$/', '', $string); 

这将替换出现在字符串开头或结尾的任何非单词字符(请注意,这不包括下划线).| 是一个交替,它将匹配任何匹配左边模式或右边模式的字符串.

This will replace any non-word characters (note this doesn't include underscores) which appear either at the beginning or end of the string. The | is an alternation, which will match any string which matches either the pattern on the left or the pattern on the right.

如果您还需要删除下划线,请使用这样的字符类:

If you also need to remove underscores, use a character class like this:

$string = preg_replace('/^[\W_]+|[\W_]+$/', '', $string);