note 44222 deleted from function.preg-split by tularis

From: Date: Thu, 03 May 2007 22:28:26 +0000
Subject: note 44222 deleted from function.preg-split by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-126184@lists.php.net to get a copy of this message
Note Submitter: e at arix dot com ---- I needed a function to highlight strings in a piece of text that could be marked up. the task couldn't be accomplished with a single preg_replace so I wrote the code below which processes only the parts of the text _outside_ markup tags. for example: with the text: click on <a href="nowhere.html">nothing</a>! I wanted to "highlight" a string (e.g. "no"), producing: click on <a href="nowhere.html"><span class="hilite">no</span>thing</a>! and not: click on <a href="<span class="hilite">no</span>where.html"><span class="hilite">no</span>thing</a>! hope this helps someone! <?php function hilites($search, $txt) { $r = preg_split('((>)|(<))', $txt, -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = 0; $i < count($r); $i++) { if ($r[$i] == "<") { $i++; continue; } $r[$i] = preg_replace( "/($search)/i", "<span class='hilite'>\\1</span>", $r[$i] ); } return join("", $r); } ?>

« previous php.notes (#126184) next »