2017-02-20 48 views
-1

我要找到一个字符串所需单词,然后我告诉马克或突出如何找到搜索词后位置转换为字符串标注这一

$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”;
回声发现后 - >这是一个“测试”“测试”“测试”功能

+1

什么是你的期望输出 –

+1

问题是什么? – RomanPerekhrest

+0

为什么不只是'str_replace('tes','tes',$ str)'? –

回答

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; 
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); 
+0

(搜索 - > tes)(回声 - >这是“测试”“测试”功能的“测试”) – user3445955

+0

这是一个更好的方法,我不认为OP希望字边界尽管。看起来'tes'只是介绍。我认为'(\ S * tes \ S *)'是OP所需要的。 – chris85

+0

@ user3445955您的预期输出是什么? – Philipp

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; 

DEMO

+0

搜索词“测试测试”时为什么不工作? – user3445955

+0

@ user3445955,因为在上面的方法中它们是不同的数组元素。 –

+0

@ user3445955如果您的字符串已修复,您可以使用.http://sandbox.onlinephpfunctions.com/code/a0631c0348fd3fc89d3a1e83c8a48547d9548850 –

相关问题