我将在字符串中找到所需的单词,然后我会显示标记或突出显示
$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
搜索 - &gt; 'TES';
发现后的回声 - &gt;这是“测试”“测试”功能的“测试”
答案 0 :(得分:1)
似乎很复杂.. 您不必拆分整个文本来进行替换
$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);
答案 1 :(得分:0)
你可以试试这个:
$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;
答案 2 :(得分:0)
$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;