Hi,

I'm kinda stumped on how to do the following:

Lets say I have a string $a, and a user supplied query $_POST['string'], I am trying to replace the user's search string in $a with a bold version of what he is searching for. So for example:

<?php

$a = "This is an apple tree.";

str_replace($POST['string'], "<strong>".$POST['string']."</strong>", $a);

print $a;

?>

That works fine, but lets say the user types his query in all caps, I can use the case insensitive version of str_replace (str_ireplace). However, the printed string will end up having letters in the middle that are all caps.

I want to keep the proper case of the original string but I can't seem to figure out a proper way of doing so. It should look like this:

user search string: APPLE
print $a: "This is an <strong>apple</strong> tree."

Thanks in advance.

    I'd say use regular expressions:

    $pattern = '/(' . $_POST['string'] . ')/i';
    $replace = '<strong>$1</strong>';
    
    $a = preg_replace($pattern, $replace, $a);

      or you could use strtolower() on the user submission.

        Right, but if they searched for 'THIS' then the resulting string would be 'this is an apple tree' instead of 'This is an apple tree'.

          How about:

          if($stringPosition = stripos($a, $_POST['string']))
          {
          	$stringLength = strlen($_POST['string']);
          	$stringToModify = substr($a, $stringPosition, $stringLength);
          	$a = str_replace($stringToModify, "<strong>".$stringToModify."</strong>", $a);
          
          print($a);
          }

          The stripos will find the position of the search string with a case insensitive search. If a match is found, then find the length of the search string. Using the position and length of the search string, grab the actual string from the original using substr (This will preserve any capitalization in the original string). Now, all that's left is to replace the original occurrances of the search string with the modified replacement string.

          Voila!🆒

            Write a Reply...