Search code examples
phpstringpoststr-replacestrpos

Use strpos to search and then highlight the matched letters


I want to perform a search on the $search string and then display the entire $search string with the matching letters highlighted.

This is the code so far:

//The user input
$user_input= $_POST['user_input'];

//The search
$search = 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.'; 

$match = strpos($search, $user_input);
echo '$match';

?>

Solution

  •     <?php
    
        //The search
        $testar = 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.'; 
    
        $match = str_replace($_POST['user_input'], '<b>' . $_POST['user_input'] . '</b>', $testar);
        echo $match;
    
         ?>