0

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.

HelloWorld
  • 2,375
  • 5
  • 22
  • 21
  • possible duplicate of [case-insensitive matching in xpath?](http://stackoverflow.com/questions/2893551/case-insensitive-matching-in-xpath) – Phil Jan 14 '14 at 02:43
  • And what have you tried so far? As written, we have no context to insert a solution into your current code. – bishop Jan 14 '14 at 02:45
  • A solution does not have to fit into my code. I'm using XML but a simple string sample would suffice. – HelloWorld Jan 14 '14 at 04:40
  • You are basically asking us to write all parts of the code for you, which isn't how SO works. Give us a starting a point and tell us where you're stuck, then you'll get constructive answers. – bishop Jan 14 '14 at 12:46
  • I've got the XML processing code and a lot more. The question has already been answered, didn't take much. – HelloWorld Jan 15 '14 at 00:56

1 Answers1

0

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

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • It does, I was however hoping that I could do it without regular expressions since they don't make any sense to me. Can you explain what all those symbols mean? – HelloWorld Jan 14 '14 at 04:42
  • Can you rewrite the regular expression so that it highlights multiple terms? – HelloWorld Jan 14 '14 at 05:17