drk49438 2014-05-02 14:36
浏览 134
已采纳

PHP正则表达式在前两个任意字符后替换数字

I need help in fixing a string, i need to remove DIGITS from a string using "preg_replace" after the first two any characters of the string, examples can be:

  1. N02 [ Should remove 2 ]
  2. AX1001 [ Should remove 1001 ]
  3. AR2003 [ Should remove 2003 ]
  4. AR [ out put should be AR, because there are no digits ]

Currently am using: preg_replace( '/\d/', '', "A0123" );

But it removes digits from the start. Any one can help?

UPDATE:
AXZ1001 : in this case it should product AXZ
AX1001 : in this case it should product AX
A1001 : in this case it should product A1

  • 写回答

1条回答 默认 最新

  • doujiu8145 2014-05-02 14:39
    关注

    You can use the \K feature:

    $str = preg_replace('~\A.{2,}?\K[0-9]+~', '', $str);
    

    Where \K removes all on the left from match result.

    Since .{2,}? is a lazy quantifier, the fewest characters (but at least 2) are matched until a digit is found. It can be replaced by a greedy version with: ..[^0-9]*

    If you want to deal with this kind of string: ABC123XYZ999 to obtain ABCXYZ:

    $str = preg_replace('~(?:\A..|(?!\A)\G)[^0-9]*\K[0-9]+~', '', $str);
    

    \G is an anchor for the end of the last match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?