note 44222 added to function.preg-split

From: Date: Sun, 18 Jul 2004 18:51:12 +0000
Subject: note 44222 added to function.preg-split
Groups: php.notes 
Request: Send a blank email to php-notes+get-73567@lists.php.net to get a copy of this message
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); } ?> ---- Manual Page -- http://www.php.net/manual/en/function.preg-split.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+44222 Delete -- http://master.php.net/manage/user-notes.php?action=delete+44222&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+44222&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#73567) next »