首页 > 解决方案 > 如何向匹配和不匹配字符串的关键字添加一些 HTML

问题描述

我有下面的代码,如果在变量 $text 中找到,则在变量 $keywords 中的关键字旁边添加一个绿色勾号,因此 Microsoft 和 Intel。现在这工作正常,但我还想在与 $text 中的关键字不匹配的关键字旁边添加一个红色勾号,即诺基亚。因此,所需的输出应该是 Microsoft 和 Intel 旁边的绿色勾号和诺基亚旁边的红色勾号。

<?php

$text = array("microsoft","intel","nokia");
$keywords = array("microsoft","intel");

foreach ($text as $str) {

  foreach ($keywords as $keyword)

     $str = preg_replace("~(?<!\w)".preg_quote($keyword, "/")."\$~i", "<i class='fa fa-check-circle' style='font-size:15px;color:green'></i> $0</span>", $str);

     $string[] = $str;

}
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<?php

foreach ($string as $strings) {

echo $strings.'<br>';

}

?>

</body>
</html> 

标签: phphtml

解决方案


我不会为这个任务使用正则表达式。

而是让您的关键字成为数组的键(而不是值),这样您就可以进行更快的查找,然后只需检查字符串是否在该数组中(作为键)。如果是这样,请将颜色变量设置为绿色,否则设置为红色。然后在单词中添加相应的刻度符号:

$text = array("microsoft","intel","nokia");
$keywords = array_flip(array("microsoft","intel"));

foreach ($text as $str) {
    $color = isset($keywords[$str]) ? "green" : "red";
    $string[] = "<i class='fa fa-check-circle' style='font-size:15px;color:$color'></i> $str";
}

foreach ($string as $strings) {
    echo "$strings<br>\n";
}

推荐阅读