Question

I just got finished coding this recursive function (my first one). It takes in $data, either an array or string, and an array of $terms to match against. It then matches, gets the entire word (not just cut off) and then adds an HTML span around it.

It works currently, but I was wondering is some of you might have some optimizations or tips to speed up a function as it can get quite heavy depending on the amount of data passed through...

public function highlight($data, $terms) {
if (!is_array($data)) {
    // We finally reached a string
    foreach ($terms as $t) {
    $pos = stripos($data, $t);
    while ($pos !== FALSE) {
        $temp_term = null;
        $match = null;
        if (preg_match('/\w+\b/', $data, $match, 0, $pos)) {
        $temp_term = $match[0];
        $len = $pos + strlen($match[0]);
        $data = substr($data, 0, $pos) . "<span class='highlight'>{$temp_term}</span>" . substr($data, $len);
        $pos = stripos($data, $t, $len + 31); // Add the span length
        } else {
        $pos = FALSE;
        }
    }
    }
} else {
    // Gotta keep looping through the arrays
    foreach ($data as &$d) {
    $d = $this->highlight($d, $terms);
    }
}

return $data;
}
Was it helpful?

Solution

Not about optimization but more easier:

$txt = 'I just got finished coding this recursive function (my first one). It takes in $data, either an array or string, and an array of $terms to match against. It then matches, gets the entire word (not just cut off) and then adds an HTML span around it.';
$r = preg_replace('/(array|word|span)/', '<b>${1}</b>', $txt);
echo'<pre>',print_r($r),'</pre>';

Output is:

I just got finished coding this recursive function (my first one). 
It takes in $data,either an <b>array</b> or string, and an <b>array</b> of $terms 
to match against.
It then matches, gets the entire <b>word</b> (not just cut off) 
and then adds an HTML  <b>span</b> around it
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top