2010-03-20 6 views
25

comment écrire le script, qui menchion le mot entier, si elle contient le mot-clé? exemple: mot-clé "fun", chaîne - l'oiseau est drôle, résultat - l'oiseau est * drôle *. je fais lemettre en évidence le mot dans la chaîne, si elle contient le mot-clé

suivant
 $str = "my bird is funny"; 
    $keyword = "fun"; 
    $str = preg_replace("/($keyword)/i","<b>$1</b>",$str); 

mais menshions mot-clé seulement. mon oiseau est amusant ny

Répondre

39

Essayez ceci:

preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str) 

\w*? correspond à tous les caractères de mot avant la mot-clé (au moins possible) et \w* tout mot caractères après le mot-clé.

Je vous recommande d'utiliser preg_quote pour échapper au mot-clé:

preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str) 

Pour le support Unicode, utilisez le u drapeau et \p{L} au lieu de \w:

preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b>$0</b>", $str) 
+0

Félicitations, ça fonctionne, merci – Simon

+0

+1 Cela fonctionne et une réponse rapide Pourquoi le? dans le modèle? – sberry

+0

@ sberry2A: expressions régulières PCRE sont par défaut, cela signifie qu'un quantificateur est étendu au maximum de la répétition possible, le '? 'rend le quantificateur non répréhensible afin qu'il corresponde le moins possible à des répétitions. (Voir aussi http://www.regular-expressions.info/ repeat.html) – Gumbo

4

Vous pouvez effectuer les opérations suivantes:

$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str); 

Exemple:

$str = "Its fun to be funny and unfunny"; 
$keyword = 'fun'; 
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str); 
echo "$str"; // prints 'Its <b>fun</b> to be <b>funny</b> and <b>unfunny</b>' 
+0

@codaddict je sais que, dans-expressions régulières signifie $ la fin de quelque chose. mais qu'est-ce que cela signifie dans votre script? et pourquoi {simbols, au lieu de (? – Simon

+0

@Syom: Ceci est seulement pour PHP de faire la distinction entre les variables et le contenu de chaîne littérale dans les déclarations de chaînes entre guillemets doubles: '" $ foobar "' sera évalué à la valeur de $ foobar '" ($ foo} bar "'/'" $ {foo} bar "' sera évalué à la valeur de '$ foo' concaténée avec' bar' Voir http://php.net/manual/fr/language .types.string.php # language.types.string.parsing pour plus d'informations – Gumbo

-2

Recherche et mettre en évidence la mot dans votre chaîne, texte, corps et paragraphe:

<?php $body_text='This is simple code for highligh the word in a given body or text'; //this is the body of your page 
$searh_letter = 'this'; //this is the string you want to search for 
$result_body = do_Highlight($body_text,$searh_letter); // this is the result with highlight of your search word 
echo $result_body;   //for displaying the result 
function do_Highlight($body_text,$searh_letter){  //function for highlight the word in body of your page or paragraph or string 
    $length= strlen($body_text); //this is length of your body 
    $pos = strpos($body_text, $searh_letter); // this will find the first occurance of your search text and give the position so that you can split text and highlight it 
    $lword = strlen($searh_letter); // this is the length of your search string so that you can add it to $pos and start with rest of your string 
    $split_search = $pos+$lword; 
    $string0 = substr($body_text, 0, $pos); 
    $string1 = substr($body_text,$pos,$lword); 
    $string2 = substr($body_text,$split_search,$length); 
    $body = $string0."<font style='color:#FF0000; background-color:white;'>".$string1." </font> ".$string2; 
    return $body; 
    } ?> 
+0

Ceci est un exemple très simple, vous pouvez simplement copier coller et changer en fonction de votre exigence .. –

+0

vos solutions contient le même problème que l'OP demande, il met uniquement en évidence les caractères correspondant au mot-clé, pas le mot contenant les caractères. –

1
<?php 
$str = "my bird is funny"; 

$keyword = "fun"; 
$look = explode(' ',$str); 

foreach($look as $find){ 
    if(strpos($find, $keyword) !== false) { 
     if(!isset($highlight)){ 
      $highlight[] = $find; 
     } else { 
      if(!in_array($find,$highlight)){ 
       $highlight[] = $find; 
      } 
     } 
    } 
} 

if(isset($highlight)){ 
    foreach($highlight as $replace){ 
     $str = str_replace($replace,'<b>'.$replace.'</b>',$str); 
    } 
} 

echo $str; 
?> 
+0

Utilisez 'str_ireplace()' au lieu de 'str_replace()' qui est la version insensible à la casse de 'str_replace()' –

-1

ici par am ou recherche multi dans une chaîne pour votre référence

$keyword = ".in#.com#dot.com#1#2#3#4#5#6#7#8#9#one#two#three#four#five#Six#seven#eight#nine#ten#dot.in#dot in#"; 

$keyword = implode('|',explode('#',preg_quote($keyword))); 

$str = "PHP is dot .com the amazon.in 123455454546 dot in scripting language of choice."; 

$str = preg_replace("/($keyword)/i","<b>$0</b>",$str); 
echo $str; 
+0

Thanks Walery Strauch – Johnson

Questions connexes