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 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?