Jump to content

[SOLVED] bold string from array of keywords


The Little Guy

Recommended Posts

Here is my code:

<?php
function boldText($string, $array){
$string = strip_tags($string);
return preg_replace('~\b('.implode('|', $array).'[a-zA-Z]{0,45})\b(?![^<]*[>])~is',
        '<strong>$0</strong>',
        $string
    );
}
?>

 

This will bold all words that contain any word in the array, so if the string is my superman cat and I search for super I would like the word super to be bold in superman so, when the results come back from my search, I would like it to display like this:

my superman cat

try

<?php
function boldText ($str, $srch)
{
    $res = '';
    $rplc = array();
    
    foreach ($srch as $s)
    {
        $rplc[] = "<strong>$s</strong>";
    }
    return str_replace ($srch,$rplc,$str);
}

$str = 'my superman cat';

echo boldText ($str, array('super', 'at'));

?> 

At that point...probably regular expressions...it's the best way I can think of at least.  Try:

 

<?php
$myWords = array('super', 'at');
function boldText($arrWords, $strSubject)
{
     if (!is_array($arrWords)) return;
     foreach ($arrWords as $strWord)
     {
          $strSubject = preg_replace('@(' . preg_quote($strWord, '@') . ')@i', "<b>\\1</b>", $strSubject);
     }
     return $strSubject;
}
print boldText($myWords, 'my SuPeRman cat');
?>

Tested under PHP 5.2.1 and works...in a few minutes I'll bring up reports as to how long it takes.

 

Edit: Got the "report"

Speed results:

My function versus Barand's function:

me@server:/path$ php -f boldText.php 
Running 10000 cycles of function boldText_Glyde()
Cycles finished in 0.18140411377 seconds
Running 10000 cycles of function boldText_Barand()
Cycles finished in 0.121095895767 seconds

 

You either deal with the inconvenience of case-changing and go for the faster one, or take a slightly longer amount of time and have it output the way you want.  Either way, those are the results.

Mine works also... I just forgot 2 things:

<?php
$array = array('this is a TEST', 'oh test it');

global $find;
$find = 'test';
function boldText($subject) {
	global $find;
	$s = preg_quote($find);
	$subject = preg_replace("/($s)/i", '<strong>$1</strong>', $subject);
	return $subject;
}

$array = array_map('boldText', $array);
print_r($array);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.