查找不区分大小写的字符串并替换(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.
我正在使用SimpleXML从XML文档中获取一些数据,如果数据包含搜索词,那么我想要 它强调。 因此,用户首先输入搜索词,然后逐个元素地处理XML文档,并执行字符串搜索。 我已经知道如何使用SimpleXML,但我不太确定如何找到不区分大小写的字符串并将其替换为自身加上一些标记。 p>
- 用户 输入“brown fox”(不带引号)作为搜索词。 li>
- Web服务器遍历所有XML元素并查找不区分大小写的匹配(每个元素一个或多个)。 li >
- 如果存在匹配(一个或多个),则不区分大小写的术语将替换为自身和一些用于标记的HTML代码。 否则,元素文本只会在没有标记的情况下输出。 li>
ul>
如果文档包含:“快速的棕色狐狸跳过懒狗。” 然后输出应该是相同的字符串,但通过CSS突出显示“棕色狐狸”。 p> div>
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
?>