Jump to content

Replacing Text


adam84

Recommended Posts

I have a textfield where the user enters a keyword about whatever they are looking for. I send the data to my php file to be processed and what I want to do is highlight the keyword that the user entered in, when I display the all the results that have matched the keyword.

What I did was use the str_replace() function, but what I have noticed is the function is case sensitive. So if the user enters 'beer'. Only the word 'beer' will get highlighted, but 'Beer', 'beeR' or 'BEER'. What would I need to do, to make it work on every instance of the word.

Link to comment
Share on other sites

Dreamhost hasn't upgraded to PHP 5.0 -- I came up with my own alternative, trying to make it run as much like str_ireplace() as possible.  Adjust the switch-a-roo token if you think it may conflict with your needle in teh haystack.

 

## HOMEBREW str_ireplace() FOR PRE-PHP 5.0

if (!function_exists('str_ireplace')  {

  function str_ireplace($search,$replace,$subject) {

    $token = '^[[term^]';

    $haystack = strtolower($subject);

    $needle = strtolower($search);

    while (($pos=strpos($haystack,$needle))!==FALSE)  {

      $c++;

      $subject = substr_replace($subject,$token,$pos,strlen($search));

      $haystack = substr_replace($haystack,$token,$pos,strlen($search));

    }

    while (($pos=strpos($subject,$token))!==FALSE)  {

      $subject = substr_replace($subject,$replace,$pos,strlen($token));

    }

    return $subject;

  }

}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.