dqve65954 2013-07-30 21:30
浏览 49
已采纳

preg_replace与单词之间的两个空格不匹配

i need to format uppercase words to bold but it doesn't work if the word contains two spaces

is there any way to make regex match only with words which end with colon?

$str = "BAKA NO TEST: hey";    
$str = preg_replace('~[A-Z]{4,}\s[A-Z]\s{2,}(?:\s[A-Z]{4,})?:?~', '<b>$0</b>', $str);

output: <b>BAKA NO TEST:</b> hey

but it returns <b>BAKA</b> NO TEST: hey

the original $str is a multiline text so there are many lowercase and uppercase words but i need to change only some

  • 写回答

2条回答 默认 最新

  • duanmo7075 2013-07-30 21:45
    关注

    You can do it like this:

    $txt = preg_replace('~[A-Z]+(?:\s[A-Z]+)*:~', '<b>$0</b>', $txt);
    

    Explanations:

    [A-Z]+      # uppercase letter one or more times
    (?:         # open a non capturing group
        \s      # a white character (space, tab, newline,...)
        [A-Z]+  #
    )*          # close the group and repeat it zero or more times
    

    If you want a more tolerant pattern you can replace \s by \s+ to allow more than one space between each words.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序