How can I remove leading and trailing non-alphanumeric characters

后端 未结 2 1681

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

Help me convert #str|ng# to st

2条回答
  •  误落风尘
    2020-12-07 06:02

    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); 
    

提交回复
热议问题