douruduan8812 2013-11-01 17:04
浏览 36
已采纳

PCRE正则表达式。 从字符串2的末尾删除字符串1,任意数量的*字符

So - I have strings like this (string1 examples):

'aaaaabbbbbcccccword'
'aaaaabbbbbcccccwor*d'
'aaaaabbbbbcccccw**ord*'
'aaaaabbbbbccccc*word*'

And I need to remove some substring (string2) from the end of those strings along with any * characters in string2 a well as * preceding string2 and following string2. string2 is some variable. I can't think of a regex that can be used here.

//wrong example, * that might happen to be inside of $string1 are not removed :(
$string1 = 'aaaaabbbbbcccccw**ord*';
$string2 = 'word';
$result = preg_replace('#\*?' . $string2 . '\*?$#', '', $string1);

Can someone suggest a PCRE regex for that?

P.S. Can I get upvoted to like at list 15 points? SO I can upvote people?

  • 写回答

2条回答 默认 最新

  • dqqxkq4047 2013-11-01 17:10
    关注
    $regexp = '#\**' . implode('\**', str_split($string2)) . '\**$#';
    $result = preg_replace($regexp, '', $string1);
    

    DEMO

    str_split splits the string up into characters, and then implode inserts \** between each of them. Then we put \** before and after it to grab any surrounding * characters as well.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?