doulu2576 2017-07-05 13:07
浏览 25
已采纳

通过传递特定模式替换中间字符串

I want to replace a middle string by passing the pattern. I have tried it by using pre_replace function. But it is not working for me.

   $str = "Lead for Nebhub - Admark
          Name: Punam Kalbande
          Email: kalbandepunam@gmail.com
          Phone Number: 800-703-3209
          Nebhub Partner : Nebhub - Admark
          Address: PO Box 830395 Miami, FL 33173
          Hub : Automotive
          Products: ERP, CRM, HCM, Help Desk, Marketing";
  $pattern = '/^Hub :(.+)Products:$/i';
  $replacement = "Logistics";
  $result = preg_replace($pattern, $replacement, $str);

but the above code is only returning original string. It is not replacing with the new one.

  • 写回答

1条回答 默认 最新

  • douyou1937 2017-07-05 13:11
    关注

    The s-Modifier is missing in your Pattern. Further you want to match the Pattern somewhere in the middle of the Text. You used ^, which indicates the Start of the Line and $ which indicates the End of the Line. That means, the whole String must match. Use this Regex, and it will work for you.

    /(Hub :)[^
    ]+/is
    

    Explanation:

    (        start Subpattern
    Hub      the Word Hub
             followed by a space
    :        followed by a Doubledot 
    )        end Subpattern -> accessible by $1 or \1
    [^
    ]+   match one or more Characters except a Linebreak
    
    i        Modifier for caseinsensitive Search
    s        Modifier to include Linebreaks
    

    What you have to do now is to output the Subpattern in the Replacement too:

    $result = preg_replace($pattern, "$1$replacement", $str);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿