duanlan2003 2014-01-14 02:40
浏览 122
已采纳

查找不区分大小写的字符串并替换(PHP)[关闭]

I'm using SimpleXML to get some data from an XML document and if the data contains a search term then I want it highlighted. So the user would first enter a search term and then the XML document is processed, element by element, and a string search performed. I already know how to use SimpleXML but what I'm not very sure is how to find a case-insensitive string and replace it with itself plus some markup.

  • User enters "brown fox" (without the quotes) as a search term.
  • Web server loops through all XML elements and looks for a case-insensitive match (one or more per element).
  • If there is a match (one or more) the case-insensitive term is replaced with itself and some HTML code for markup. Otherwise the element text is just outputed without markup.

If the document contains: "The quick brown fox jumps over the lazy dog." then the output should be the same string but with "brown fox" highlighted via CSS.

  • 写回答

1条回答 默认 最新

  • dongzhimeng2464 2014-01-14 02:52
    关注

    This may work for you:

    <?php
    $html = "The quick brown fox jumps over the lazy dog";
    $replace = preg_replace('/\A(.*?)(brown fox)(.*?)\z/sim', '$1<span STYLE="font-size: x-large; color: #ffffff">$2</span>$3', $html);
    echo $replace;
    // The quick <span STYLE="font-size: x-large; color: #ffffff">brown fox</span> jumps over the lazy dog
    ?>
    

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?