douhua9726 2017-11-09 12:33
浏览 107
已采纳

preg_replace除字符串开头之外的所有数字和星号字符

Need to replace all characters in a string except for any that are at the start of a string (or part of a word).

For example input:

MSFT *<E07004QY6W>
WOOLWORTHS W1157
GOOGLE*ADWS7924436927
COLES 0829
ROBLOX.COM 888-858-25
7-ELEVEN 2179
COLES EXPRESS 1896

result should be:

MSFT
WOOLWORTHS
GOOGLE
COLES
ROBLOX.COM
7-ELEVEN
COLES EXPRESS

Can php preg_replace achieve this?

Tried so far:

  • '/\d+/g' - but it removes ALL digits and nothing else
  • '/(*|\d+$)/' - but this doesn't quite work on some, results in "ROBLOX.COM 888-858-"
  • 写回答

2条回答 默认 最新

  • dq05304 2017-11-09 12:49
    关注

    Not sure this will work for other edge cases, but you can try with this replacement:

    $txt = preg_replace('~^[^*\s]+(?: \pL+(?!\S))*\K.*~m', '', $txt);
    

    demo

    Explanations:

    ^[^*\s]+ takes all that isn't a space or an asterisk at the start of the line.
    (?: \pL+(?!\S))* and eventually group of letters separated by spaces.
    \K removes all previous matched characters from the match result.
    .* takes all the remaining characters that will be replaced.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!