php - 如何向匹配和不匹配字符串的关键字添加一些 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>
解决方案
我不会为这个任务使用正则表达式。
而是让您的关键字成为数组的键(而不是值),这样您就可以进行更快的查找,然后只需检查字符串是否在该数组中(作为键)。如果是这样,请将颜色变量设置为绿色,否则设置为红色。然后在单词中添加相应的刻度符号:
$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";
}
推荐阅读
- typescript - 为什么常规函数会破坏类型推断?
- jquery - 调用 load() 函数后,ajax 调用不起作用
- reactjs - 在d3 csv中多次调用函数
- python - 我想在旁边显示每个部门的员工姓名。我怎么能在 Django 中做到这一点?
- python - Series 的真值是不明确的。使用 a.empty()、a.bool()、a.item()、a.any() 或 a,all()
- c++ - 为什么输出会不同,因为两个 c++ 语句都在执行相同的操作
- linux - 当我删除 tham 时,Smth 会在我网站的根目录中自动创建 php 文件(被黑的 wordpress)
- node.js - 是否可以查明 Node.js 当前是否使用 `--harmony` 或 `--es_staging` 标志运行?
- c++ - 如何在archlinux上安装旧的QT版本?
- python - 生产模式和部署的 Setting.py 配置