2017-06-06 105 views
0

我有一个脚本,需要一些改进。基本上它所做的是接受一个字符串,然后尝试在另一个字符串内搜索该字符串以在其周围插入一些HTML以用于突出显示。插入标签到搜索字符串/字符串案例

目前,它看起来像这样:

$query = $_POST['$query']; 
$searched = "New York Yankees in New York"; 

str_ireplace($query,"<span class='hilight'>".$query."</span>", $searched); 

现在,它的工作原理,但奇怪的行为(可预测的),当它涉及到大/小写。

说$查询=“新” ..返回的字符串是:

<span class='hilight'>new</span> York Yankees in <span class='hilight'>new</span> York. 

,你会如何去完成同样的事情,在不改变原有搜索的字符串的情况下?

+0

当然了正则表达式! –

回答

0

简单的办法就是使用正则表达式和preg_replace功能:

$query = 'new'; 
$searched = "New York Yankees in New York"; 
$r = preg_replace("/($query)/i", "<span class='hilight'>$1</span>", $searched); 
echo'r is: ',$r; 

所以,主要的动作在这里不用在preg_replace

preg_replace(
    // find substring `$query`, flag `i` means case-insensitive search 
    "/($query)/i", 
    // replace founded occurences with this string, `$1` here means the value of the founded substring (`new` or `New` or even `NEW`) 
    "<span class='hilight'>$1</span>", 
    // string where to find 
    $searched 
);