Skip to content

Instantly share code, notes, and snippets.

@A35G
Created November 14, 2024 10:22
Show Gist options
  • Select an option

  • Save A35G/57e138814a37ca495f7383cbd2cf8f22 to your computer and use it in GitHub Desktop.

Select an option

Save A35G/57e138814a37ca495f7383cbd2cf8f22 to your computer and use it in GitHub Desktop.
Searching and highlighting one or more words in a text - Example with string/text predefined
<?php
function highlightText(string $str, array $keyw = [], bool $accurate = false)
{
if (empty($keyw)) return false;
$sText = implode('|', $keyw);
$match = ($accurate) ? '@\b(' . $sText . ')\b@si' : '@(' . $sText . ')@si';
return preg_replace(
$match,
'<strong style="background-color:yellow">$1</strong>',
$str
);
}
function searchText(string $mystring, string $word)
{
$offset = $pos = 0;
$arrPos = [];
do {
$pos = stripos($mystring, $word, $offset);
if (is_integer($pos)) {
$arrPos[] = $pos;
$offset = ($pos + strlen($word));
}
} while(is_integer($pos));
if (!empty($arrPos)) return $arrPos;
return false;
}
if (isset($_POST['keyws']) && !empty($_POST['keyws'])) {
$mystring = "This will be the text that will be highlighted with our little function in PHP.";
$dw = htmlentities($_POST['keyws']);
$dw = trim($dw);
if (!empty($dw)) {
$words = explode(" ", $dw);
$ccn = count($words);
$notfound = 0;
foreach($words as $word) {
$findIt = searchText($mystring, $word);
if (!$findIt) ++$notfound;
}
echo (empty($notfound) OR $notfound < $ccn)
? highlightText($mystring, $words, true)
: "No matches found with the words indicated.";
}
}
echo "
<form name='frmSearch' method='POST' action='" . $_SERVER['PHP_SELF'] . "'>
<input type='text' name='keyws' value='' />
<input type='submit' value='Search' />
</form>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment