开发者

term highlight algorithm (HTML)

I know there are quite some term highlighting questions asked but as far as I know none answers mine. The search terms are put into an array

$keyarray = array("DE", "ABCD");
$string = "ABCDEF";
foreach ($keyarray as $value) {
   $string = str_ireplace($value, "<b>{$value}</b>", $string);
}

The results will obviously be ABCDEF rather than ABCDEF So its there anyway way that I can highlight both terms using a BOLD tag ext开发者_StackOverflowremely fast using PHP?


"Extremely fast" is a relative term. That aside, you have a couple of options:

  • Regular Expressions: if you are very good with regexes, this is a valid use for them. You can also look forward/behind with them, which allows for a fair amount of flexibility.

http://www.regular-expressions.info/lookaround.html

  • Character by character parse: this is often the best way of doing string manipulation (and fastest), but can be the most time-consuming to create.

  • String replaces; fast but there's usually an edge case that doesn't work correctly (speaking from experience).

In all of these scenarios, you can benefit from pre-optimizing your list of terms by sorting/grouping/filtering them appropriately. For example, sorting biggest to smallest length would ensure that you didn't split up a long string (and miss a match) by bolding a shorter string within it.

You could also predetermine optimal regex(es) by examining all the search terms before beginning the replace. Again, this would assume you are pretty savvy with regexes.


maybe use regexp like: /de|acbd/. regex is searching from left to right and it's not going back so there will be no situtation like <b>1111<b></b>112222</b>


You may try this:

$keyarray = array("DE", "ABCD");
$string = "ABCDEF";
$words = explode(' ',$string);
foreach($words as &$w){
   foreach($keyarray as $criteria) {
        if(stripos($w,$criteria)!==false){
            $w = "<b>$w</b>";
                    break;//avoid duplicate wrapping
        }
   }
}
$string = implode(' ',$words);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜