douye2110 2012-09-17 21:30
浏览 19
已采纳

preg_replace在模式之间删除字符串的多个不同部分

This is a very small portion of a string i have scraped:

SEPVALAjazz(music)SEPVALC5.59SEPVALAlatin(music)SEPVALAcountry(music)SEPVALC6.70SEPVALArock(music)SEPVALC5.89SEPVALAdance(music)SEPVALAworld(music)SEPVALC6.70

I have manipulated the string with regex to insert the "SEPVALA" and "SEPVALC" values. I wish to remove the string between the patterns "SEPVALA" and "(music)SEPVALA" where ever it occurs in the text. In the above example this would remove "latin" and "dance".

The desired result would be:

SEPVALAjazz(music)SEPVALC5.59SEPVALAcountry(music)SEPVALC6.70SEPVALArock(music)SEPVALC5.89SEPVALAworld(music)SEPVALC6.70

The code i am implementing at the moment is:

$pattern="/SEPVALA(.+?)\(music\)SEPVALA/";

$replacement="SEPVALA";

$newstring=preg_replace($pattern, $replacement, $originalstring);

However this removes too much of the string as the regex engine picks up the very first "SEPVALA" and removes everything forward from this point until "(music)SEPVALA" (as it should do!) I need a method to scan backwards from "(music)SEPVALA" removing the offending text and stopping at the next "SEPVALA" before then moving forwards to the next match of "(music)SEPVALA" and so on. Or any other method to accomplish this. Many thanks.

  • 写回答

1条回答 默认 最新

  • douzao2992 2012-09-17 21:39
    关注

    Try replacing the following pattern with an empty string:

    SEPVALA((?!SEPVAL[AC]).)+(?<=\(music\))(?=SEPVALA)
    

    Example: http://www.rubular.com/r/ZCfJQ4ey2O

    Explanation: This works by matching SEPVALA, then matching one character at a time until either SEPVALA or SEPVALC can match, by using a negative lookahead with repetition. At this point we have matched from SEPVALA to just before either SEPVALA or SEPVALC, so we just need to make sure the previously matched characters are (music), and the next characters are SEPVALA.

    Full code:

    $pattern="/SEPVALA((?!SEPVAL[AC]).)+(?<=\\(music\\))(?=SEPVALA)/";
    $replacement="";
    $newstring=preg_replace($pattern, $replacement, $originalstring);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写