简体   繁体   English

如何只从php字符串中突出显示字符?

[英]How to get only characters highlighted from a string in php?

I have a string and some words, i want to highlight those words which match with string, and also i want to print only those words which are highlighted, like if apple matches, then only apple must be printed. 我有一个字符串和一些单词,我想突出显示与字符串匹配的单词,并且我也只想打印那些突出显示的单词,例如,如果苹果匹配,则只能打印苹果。

$string = "apple computer";

$keyword = "apple,orange,bike";

I am using the following function to highlight specific characters in a string. 我正在使用以下功能突出显示字符串中的特定字符。

$str = preg_replace("/($keyword)/i","<span style='color:orange;'>$0</span>",$string);

The problem is I want to show only those characters which are highlighted, currently it shows all the characters. 问题是我只想显示那些突出显示的字符,当前它显示所有字符。

This would meet your need. 这将满足您的需求。

$string = " apple computer orange";
$keywords = "apple, orange";

$exp_kwd = explode(",", $keywords);

$res = "<span style='color:orange;'>";

foreach($exp_kwd as $val){

    if(strpos($string, trim($val))){

       $res .=  $val." ";
    }
}
$res = $res."</span>";

echo $res;

Hopefully this also will work 希望这也会起作用

$string = "apple computer orange tested";
$keyword = "apple,orange,bike,tested";

$pattern="/".str_replace(",","/,/",$keyword)."/";
$pattern=explode(",",$pattern);

$string=explode(" ",$string);
$keyword =explode(",",$keyword);

$string=implode(",",(preg_filter($pattern, $keyword, $string)));
echo $string="<span style='color:orange;'>$string</span>";
$string = "Im On  #Here";
$keyword = "#";

$var = strrchr($string,$keyword);
if(empty($var))
{
    echo 'No Occerunce Found';
}
else
{
    echo '<span style="color:orange;">'.$var.'</span>';
}

phpfiddle Preview phpfiddle预览

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM