查找不区分大小写的字符串并替换(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.

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