douji0588 2014-02-13 19:46
浏览 42
已采纳

如何创建php正则表达式

I am trying to create a regex to replace a string. Here is my pattern:

\{mailMerge: details_activity_number\\}

When I do a search like this on a string like this:

hello {mailMerge: details_activity_number\}world

its fine. But, if there's a line break like this:

hello \{
mailMerge: details_activity_number\} world

it breaks. Here is my code in PHP:

 $pattern = '\{mailMerge: 'mailMerge: details_activity_number'\}';
 $content =  str_replace($pattern, $value, $content);

Can anyone help me with creating a pattern that would take into consideration possible line breaks/white spaces/etc to guarantee a match?

thanks

EDIT

private function  findAndReplace($content, $mergedArray){
    $test=$content;
    try{
        foreach($mergedArray as $ArrayKey => $ArrayValue){
            foreach ($ArrayValue  as $key => $value) {               
                $pattern = "\{\s*mailMerge:\s+". $key ."\s*\\\}";

                if($value){
                    $test =  preg_replace($pattern, $value, $test);
                }else{
                    $test =  preg_replace($pattern, "No Value Exists", $test);
                }
            }
        }
    }catch(Exception $e){
        throw $e;
    }
    return $test;
}
  • 写回答

1条回答 默认 最新

  • donglinxi1467 2014-02-13 19:49
    关注

    The first version that you posted doesn't allow for any space between { and m. You need to do something like this:

    \{\s*mailMerge:\s+details_activity_number\s*\\\}
    

    The \s* means "match zero or more spaces (or other white space, like new lines) here." \s+ means "match one or more spaces (or other white space, like new lines) here."

    NOTE: Your code above uses str_replace, but you are trying to do a regex replace. You need to use preg_replace instead of str_replace, like in this code:

    $content = "\{mailMerge: 'mailMerge: details_activity_number'\}";
    $content =  preg_replace('/\{\s*mailMerge:\s+details_activity_number\s*\\\}/m', $value, $content);
    

    EDIT BASED ON COMMENTS: Try this; it is working for me.

    $value = "foo barrrrrr";
    
    $content = "hello
    {mailMerge: details_activity_number\} world";
    
    $content =  preg_replace("/\\\\?\\{\s*mailMerge:\s+details_activity_number\s*\\\\?\\}/m", $value, $content);
    
    echo $content; // produces "hello foo barrrrrr world"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?