我刚刚完成了这个递归函数的编码(我的第一个递归函数)。它接受$data,一个数组或字符串,以及一个要匹配的$terms数组。然后它匹配,得到整个单词(不只是截断),然后在它周围添加一个HTML span。
它目前工作,但我想知道你们中的一些人可能有一些优化或技巧来加速一个函数,因为它可以变得相当重,这取决于通过的数据量…
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;
}
不是关于优化,而是更容易:
$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>';
输出是:
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