Zend - The PHP Company




Text

Add Code


Highlight  

Type: code fragment
Added by: Souldrinker
Entered: 10/08/2001
Last modified: 08/12/2000
Rating: - (fewer than 3 votes)
Views: 5474
This Function allows it to highlight assigned Parts (needle) of a string (hystack) with pre defined HTML-Tags by only once call of function. Surely, in PHP4 it would be much easier to realise such a function - but this function works in PHP3, too. To define the tags that highlight the needle in the hystack-string use an array consisting of two values [0] (for opening the tag(s)) and [1] (for closing the tag(s)). The function doesn't do any echo's, it only returns the value, so you have to call it in order with echo to write what it returns.


<?php
    
function highlight($needle$hystack$hl) {

    
$needle_length    strlen($needle);                               
            
    
$cmp_hs        strtolower ($hystack); 
    
$cmp_hl        strlen     ($hystack);
    
$cmp_ne        strtolower ($needle );
        
$cmp_nl        strlen     ($needle );
                        
        
$i=0;
        
$c=0;
                        
    while(
$i<=$cmp_hl) {
                                                     
            if(
substr($cmp_hs,$i,$cmp_nl)==$needle) {
                    
$to_bold_position[$c] = $i;
            
$c++;
        }
                                
                
$i++;
        }
                        
        
$i=0;
        
$temp='';
                        
    do {
                                
            
$j         =    $i 1;                                
                
$between     =    $to_bold_position[$i] - $to_bold_position[$j];
                                
        
$temp2          =     substr($hystack,$to_bold_position[$j],$between);
                
$temp            .=    eregi_replace($needle,"",$temp2);
                
$temp         .=     "$hl[0]".substr($hystack,$to_bold_position[$i],$cmp_nl)."$hl[1]"
                                
                
$i++;   
                                                         
        } while(
$i!=$c);

    
$i=$i-1;
        
$rest $cmp_hl-$cmp_nl;
        
$last $to_bold_position[$i]+$cmp_nl;
                                                                
        
$temp .= substr($hystack,$last,$rest);
                                                     
        return 
$temp;
    
}
    
?>


Usage Example


<?php

    
include("highlight.php3");
    
    
$bt[0]="<b>";
    
$bt[1]="</b>";
    
    echo 
highlight("test","dies ist ein test - zum testen der highlightfunktion",$bt);
?>


Rate This Script





Search



This Category All Categories