我将在字符串中找到所需的单词,然后我显示标记或突出显示
$str = "this is a test for testing a test function";
$array = explode(' ',$str);
$key = array_search('tes', $array);
$tr='';
foreach($array as $i=>$ar){
if($key == $i){
$tr .= '<a style="color:red">'.$ar.'</a> ';
}else{
$tr .= $ar.' ';
}
}
echo $tr;//this is a <a style="color:red">test</a> for <a style="color:red">testing</a> a <a style="color:red">test</a> function
搜索 ->'tes';
查找之后 ->这是用于"测试"测试"功能的"测试"
似乎很复杂。您不必将整个文本分开即可进行替代:
$str = "this is a test for testing a test function";
$search = "tes";
echo str_replace($search, "<strong>$search</strong>", $str);
如果您只想搜索整个单词,则正则表达式可能会帮助您:
$search = "test";
$regex = "~b(" . preg_quote($search, '~') . ")b~";
echo preg_replace($regex, "<strong>$1</strong>", $str);
您可以尝试以下方法:
$str = "this is a test for testing a test function";
function search_array($array, $term)
{
$keys=array();
foreach ($array AS $key => $value) {
if (stristr($value, $term) === FALSE) {
continue;
} else {
$keys[]=$key;
}
}
return $keys;
}
$array = explode(' ',$str);
$term="tes";
$data=search_array($array, $term); //get keys
$tr='';
foreach($array as $i=>$ar){
if(in_array($i,$data)){//if avialable
$tr .= '<a style="color:red">'.$ar.'</a> ';
}else{
$tr .= $ar.' ';
}
}
echo $tr;
demo
$term="testing a test";
function search_array($array, $term)
{
$keys=array();
foreach ($array AS $key => $value) {
$term1 = explode(' ',$term);
foreach ($term1 AS $k => $t) {
if (stristr($value, $t) === FALSE) {
continue;
} else {
$keys[]=$key;
}
}
}
return $keys;
}
$str = "this is a test for testing a test function";
$array = explode(' ',$str);
$data=search_array($array, $term); //get keys
$tr='';
foreach($array as $i=>$ar){
if(in_array($i,$data)){//if avialable
$tr .= '<a style="color:red">'.$ar.'</a> ';
}else{
$tr .= $ar.' ';
}
}
echo $tr;