2017-01-02 6 views
2

以下は私のコードです。完全な単語と部分的な単語を強調したいと思います。下のコードはフルの単語を強調表示しますが、の部分はという単語を強調表示していません。例えばどのようにして、PHPでフルワードと部分ワードを強調表示できますか?

$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance"; 

$words ="very written hu want impor"; 

私は以下のような出力をしたい: -

「これはliegh を書か非常に famouseの詩ですhu投稿がになります。impor tance;私はそれのために作成した

機能: -

function highlight($text, $words) { 
    preg_match_all('~\w+~', $words, $m); 
    if(!$m) 
     return $text; 
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i'; 
    return preg_replace($re, '<b style="color:white;background-color:red;border-radius:2px;">$0</b>', $text); 
} 
+1

削除 '\ B'あなたが単語全体と一致しない場合。 $ words文字列に部分語と完全語の両方が含まれている場合は、https://ideone.com/cMXG0M –

+0

を参照してください。部分語と完全語の両方の強調表示を強調したいと思います。 – alex

+1

それで、言葉の境界は何ですか? –

答えて

1

ストップあなたがPHPで作り付けの機能を持っている場合、正規表現に苦労。

純粋なPHPで同じ機能。正規表現を使用せずに、大文字と小文字を区別しないでください。

<?php 

$words = "very written hu want impor"; 
$words = explode(' ', $words); 

function hilight($text, $words){ 
    foreach ($words as $value) { 
    $text = str_ireplace($value,'<b style="color:white;background-color:red;border-radius:2px;">'.$value.'</b>',$text); 
    } 
    return $text; 
} 

$text = "this is a very famouse poem written by liegh hunt the post want to impress upon the importance"; 
echo hilight($text, $words); 

?> 

enter image description here

関連する問題