如何删除PHP中的前导和尾随非字母数字字符?
I'm looking to "trim" non-alphanumerics from a string, similar to how trim()
works with whitespace.
Help me convert #str|ng#
to str|ng
.
I can remove trailing non-alphanumerics with:
$string = preg_replace('/\W+$/', '', $string); // converts `#str|ng#` to `#str|ng`
And leading with:
$string = preg_replace('/^\W+/', '', $string); // converts `#str|ng#` to `str|ng#`
But how can I accomplish both at the same time?
我希望从字符串中“修剪”非字母数字,类似于 帮助我将 我可以删除尾随的非字母数字: p>
并以: p>
但是如何同时完成两者? p> \ n div> trim() code>适用于空白。 p>
#str | ng# code>转换为
str | ng code>。 p>
$ string = preg_replace('/ \ W + $ /','',$ string); //将`#str | ng #`转换为`#str | ng`
code> pre>
$ string = preg_replace('/ ^ \ W + /','',$ string); //将`#str | ng #`转换为`str | ng#`
code> pre>
Try using a 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);
You don't need regex, use trim()
and specify what to trim (it trims whitespace by default):
$string = trim($string, "#");
Docs: http://php.net/trim