NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP STRING QUESTION

Scott Mattocks scott at crisscott.com
Tue Oct 19 14:33:50 EDT 2004


Here is something that seems to work. It isn't very elegant either but 
it does the trick.

<?php
$term = 'bob';
$phrase = 'Bob likes bobbing for apples';
$highlightStart = '<b>';
$highlightEnd = '</b>';

// Case insensative version of the string.
$lowerPhrase = strtolower($phrase);

// Position of first occurance.
$pos = strpos($lowerPhrase, $term);

// Loop through the search phrase until we don't find any more of term.
while ($pos !== false) {

   // Cut the phrase into chunks around the term and add some highlight 
chars.
   $phrase = substr($phrase, 0, $pos) . $highlightStart .
     substr($phrase, $pos, strlen($term)) . $highlightEnd .
     substr($phrase, $pos + strlen($term));

   // Capture the strpos offset.
   $oldPos = $pos + 1;

   // Recreate the lowercase string.
   $lowerPhrase = strtolower($phrase);

   // Get the next position
   $pos = strpos($lowerPhrase, $term, $oldPos + strlen($highlightStart));

   // Debug output.
   echo 'Pos ' . $pos . 'Old pos ' . $oldPos . "\n";
   echo $phrase . "\n";
   echo $lowerPhrase . "\n";
}
?>


Scott Mattocks

Russ Demarest wrote:

> It is not elegant but you can try searching for the word lowercase, then 
> search for it with an init cap then plural (add an s). Like I said not 
> elegant but 90% sufficient.
> 
> Russ
> 




More information about the talk mailing list