【问题标题】:Change class when string is found in PHP在 PHP 中找到字符串时更改类
【发布时间】:2014-11-30 14:38:39
【问题描述】:

我有:

$keyword = 'blue';

我想在系统找到blue的字符串中插入一个特殊的类。


例如:

This sky is <span class="blue">blue</a>.

This pear is green.


其实我有:

$string = "The sky is blue."; 
if (stripos($string, $keyword) !== false) {
    // The string is found, now change the class
}

非常感谢。

【问题讨论】:

  • 您是否考虑过改用javascript?
  • 我更喜欢在对 PHP 页面进行 ajax 调用时使用 PHP。

标签: php class


【解决方案1】:

这是你要找的吗?

$keyword = 'blue';
$replace = 'green';
$string = "The sky is blue."; 
if (stripos($string, $keyword) !== false) {
   $string = str_ireplace(array($keyword), $replace , $string);
}

【讨论】:

  • 真的没有。如果找到,我想用<span class="myClass">blue</span> 替换blue
  • 这就是你应该把它作为 $replace 的值。
【解决方案2】:

您可以使用正则表达式,例如:

function format_keywords($html, $keywords) {
    foreach ($keywords as $keyword) {
        $keyword = preg_quote($keyword);
        $html = preg_replace("/\b$keyword\b/i", "<span class=\"$keyword\">$keyword</span>", $html);
    }
    return $html;
}

例如,这个:

format_keywords("This sky is blue.", array("is", "blue"));

会产生:

This sky <span class="is">is</span> <span class="blue">blue</span>?

请注意,This 未被识别,这要归功于 \b 分隔符。

查看文档:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多