How can I remove leading and trailing non-alphanumeric characters

后端 未结 2 1677

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 05:57

    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

    0 讨论(0)
  • 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); 
    
    0 讨论(0)
提交回复
热议问题