dtcyv3985 2014-02-19 04:47
浏览 15
已采纳

如何删除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?

  • 写回答

2条回答 默认 最新

  • dsbezji539113152 2014-02-19 04:56
    关注

    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); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献