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 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)