如何将指定的子字符串包装在 html 标签中?

How to wrap nominated substrings in html tags?

我需要不区分大小写地定位子字符串并将它们包装在 <strong></strong> 标签中:

示例:

$q = $_GET['q'];
echo "abcdefABCDEF";

如果我搜索 "a"(例如:index.php?q=a),输出将鼓励所有出现的 "a" 和 "A",如下所示:

<strong>a</strong>bcdef<strong>A</strong>BCDEF

如何将这些标签插入到字符串中?

你可以这样做:

$q = 'o';
$original_string = 'Lorem Ipsum dolor sit amet.';

echo str_ireplace($q, '<strong>' . $q . '</strong>', $original_string);

如果您打算用 HTML 标签搜索和替换内容,请考虑使用 preg_replace()。你会发现它比 str_ireplace()

更强大
echo preg_replace('/([aA])/', '<strong></strong>', $_GET['q']);