【问题标题】:str_ireplace() with keeping of casestr_ireplace() 保留大小写
【发布时间】:2011-03-30 05:16:29
【问题描述】:

如何使用 str_ireplace(或类似的东西)来替换一些文本以进行格式化,然后用相同的大写字母返回它?

例子:

$original="The quick red fox jumps over the lazy brown dog.";
$find="thE";

print str_ireplace($find,'<b>'.$find.'</b>',$original);

这将输出: thE 敏捷的红狐跳过了懒惰的棕色狗。

我希望它保留原来的大小写并且只应用格式,在本例中为粗体文本。

谢谢。

【问题讨论】:

    标签: php match case-insensitive replace


    【解决方案1】:

    我已经编写了一个替代解决方案(一个使用纯字符串替换的函数)来完成这项工作,它允许您轻松设置前缀和后缀(用于突出显示):

    function replace_keep_case($st1, $find1) {
    
    /// set prefix and suffix here
    $prefix="<span style='color:red;'><b>";
    $suffix="</b></span>";
    
    $index=0;
    $resultstring="";
       while ($index < strlen($st1)) {
          if (strtoupper(substr($st1, $index, strlen($find1)))==strtoupper($find1)) {
            $resultstring.=$prefix.substr($st1, $index, strlen($find1)). $suffix;
            $index=$index+strlen($find1); 
          } else {
            $resultstring.=substr($st1, $index, 1);
            $index++;
          }
        }
       return $resultstring; 
    }
    

    例如:

    $text="CHICHiOn Ichiro's Malt & Grain (Limited Edition) 700ml 48% CONDITION";
    
    $findstring="ion";
    
    echo replace_keep_case($text, $findstring);
    

    【讨论】:

      【解决方案2】:

      要么替换为确切的单词,要么使用 preg_replace:

      preg_replace('/(The)/i', "<strong>$1</strong>", $original);
      

      【讨论】:

        【解决方案3】:
        $original = "The quick red fox jumps over the lazy brown dog.";
        $new = preg_replace("/the/i", "<b>\$0</b>", $original);
        

        给出“快速的红狐跳过懒惰的棕色狗。”如果要匹配特定单词,可以添加单词边界:preg_replace('/\bthe\b/i', ...

        如果要参数化替换,可以使用preg_quote

         preg_replace('/\b' . preg_quote($word, "/") . '\b/i', "<b>\$0</b>", $original);
        

        【讨论】:

        • *敏捷的棕狐跳过懒狗
        • 添加 u 修饰符以支持 UTF-8
        猜你喜欢
        • 1970-01-01
        • 2010-12-20
        • 2010-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2010-10-21
        • 1970-01-01
        相关资源
        最近更新 更多