文字列を強調表示しようとしています。それらが順番に並んでいるかどうか。このような -
$str = "star 5 hotel";
$keywords = "5 star hotels";
私の機能があります。最後に一致した$str
文字列のみが強調表示されます。ここには検索文字列が含まれています。$keyword
データベースに保存した文字列が含まれています
一致する各文字列を強調表示するにはどうすればよいですか。
function highlight($str, $keyword) {
$str = "star hotel 5";
$keyword = "5 star hotel";
foreach($look as $find){
if(strpos($keyword, $find) !== false) {
if(!isset($highlight)){
$highlight[] = $find;
} else {
if(!in_array($find,$highlight)){
$highlight[] = $find;
}
}
}
}
if(isset($highlight)){
foreach($highlight as $replace){
$str = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);
$stra[] = str_ireplace($replace,'<b>'.$replace.'</b>',$keyword);
echo "<pre>";
print_r ($stra);
echo "</pre>";
}
}
echo $str."<br>";
die();
return $str;
}
しかし、これを配列に入れて、この配列を出力すると$stra[]
。それは私にこれを与えました
配列(
[0] => 5つ星ホテル
[1] => 5つ星ホテル
[2] => 5つ星ホテル
)。
これらを組み合わせる方法が見つかりません。
出力: -検索しているキーワードがある場合。次に、これを強調表示する必要があります。
5つ星ホテル
これは私が仮定したものです:-
指定された文字列内の検索文字列の各単語を検索し、すべての単語が見つかった場合にのみ、文字列を太字(完全な文字列)にすることを想定しています。
次に、以下のようにします(コメントで説明されています):-
<?php
$search = "star 5 hotel"; //search string
$string = "5 star hotels"; // string in which you want to search
function highlight($search, $string) {
$new_search = array_unique(array_filter(explode(" " ,$search)));//explode search string
$found_count = 0; //create a counter
foreach($new_search as $find){ // iterate over search words array
if(strpos($string, $find) !== false) { // if word found in the string
$found_count +=1; // increase the counter
}
}
if(count($new_search) == $found_count){ //check that all words found in the string
$string = "<b>". $string ."</b>"; // if yes then make each word of the string bold
}
return $string; //return the newly modified string
}
echo highlight($search, $string); // echo newly modified string
出力:-https://eval.in/838325
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加