dspv70887
2012-05-15 08:05
浏览 52
已采纳

PHP正则表达式字符串格式化聊天对话框错误preg_replace()

I'm formating for a chatting dialog bellow:

  • Dalvik: Lorem ipsum dolor sit amet
  • Jenni: Suspendisse facilisis pretium ante,
  • Dalvik: Vivamus feugiat dui ut libero rhoncus nec porttitor velit posuere.
  • Jenni: Aenean porttitor ipsum eu metus adipiscing
  • Dalvik: (Sed vehicula: magna vitae nulla
  • Jenni: sed dui quam, vitae consectetur dui.
  • Jenni: Curabitur vulputate ante :)

The bold text above ; it make error in my replace statment:

$name = self::getNameFromMessage($textFormat);
$color = self::getNewTextColor();
$replacement = "<br/><font color='$color'>$name</font>:";
$textFormat = preg_replace(
           $pattern = "/$name :\s/i", //find $name in $textFormat and set text color
           $replacement, 
           $subject = $textFormat
);

Error: preg_replace() [function.preg-replace]: Compilation failed: missing ) at offset 15

Can you suggest me a better regex string?

图片转代码服务由CSDN问答提供 功能建议

我正在形成一个聊天对话框:

    < li> Dalvik:Lorem ipsum dolor sit amet
  • Jenni:Suspendisse facilisis pretium ante,
  • Dalvik:Vivamus feugiat dui ut libero rhoncus nec porttitor velit posuere。
  • Jenni:Aenean porttitor ipsum eu metus adipiscing
  • Dalvik:(Sed vehicula: magna vitae nulla
  • Jenni:sed dui quam,vitae consectetur dui。
  • Jenni:Curabitur vulputate ante:)

    上面的粗体文字; 它在我的替换语句中出错:

      $ name = self :: getNameFromMessage($ textFormat); 
     $ color = self :: getNewTextColor(); 
     $ replacement  =“&lt; br /&gt;&lt; font color ='$ color'&gt; $ name&lt; / font&gt;:”; 
     $ textFormat = preg_replace(
     $ pattern =“/ $ name:\ s / i”  ,//在$ textFormat中找到$ name并设置文本颜色
     $ replacement,
     $ subject = $ textFormat 
    ); 
       
     
     

    错误 :preg_replace()[function.preg-replace]:编译失败:丢失)偏移15

    你能建议我一个更好的正则表达式字符串吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwu5318 2012-05-15 08:07
    已采纳

    The error was caused by not quoting your regex, in your example, the regex finds a (, then it expects to find a closing ). If you want to match a literal () or other regex meta-characters, you need to quote your regex:

    $pattern = preg_quote("/$name :\s/i");
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题