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?

  • 写回答

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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退