【问题标题】:PHP: wrap (all) needle with a html element in a string haystackPHP:用字符串干草堆中的html元素包装(全部)针
【发布时间】:2011-11-26 08:49:28
【问题描述】:

对于我的自动建议功能,我需要为建议中的摘录着色......所以......

如果我搜索类似 “萨” 建议者给了我以下内容

三星 讽刺 数据 e-sata ...

现在我想从我的函数中突出显示 - 将“sa”针(所有出现)包裹在所需的 html 标记中。

喜欢 msung sa轮胎 sata e-sata

  • 应该是 utf8 安全的
  • 它应该保留大写
  • 它应该忽略 HTML

在 PHP 网站上,我找到了一个可以替换并保持大写的函数...我对其进行了修改,使其对 utf8 友好...

function ext_str_ireplace($findme, $replacewith, $text) { 
    // Replaces $findme in $subject with $replacewith 
    // Ignores the case and do keep the original capitalization by using $1 in $replacewith 
    // Required: PHP 5 

    $rest = $text; 

    $result = ''; 

    while (mb_stripos($rest, $findme) !== false) { 
      $pos = mb_stripos($rest, $findme); 

      // Remove the wanted string from $rest and append it to $result 
      $result .= mb_substr($rest, 0, $pos); 
      $rest = mb_substr($rest, $pos, mb_strlen($rest)-$pos); 

      // Remove the wanted string from $rest and place it correctly into $result 
      $result .= mb_ereg_replace('$1', mb_substr($rest, 0, mb_strlen($findme)), $replacewith); 
      $rest = mb_substr($rest, mb_strlen($findme), mb_strlen($rest)-mb_strlen($findme)); 
    } 

    // After the last match, append the rest 
    $result .= $rest; 

    return $result; 
} 

效果很好……喜欢

ext_str_ireplace("sa", "<b>sa</b>", "Samsung");

直到我将一些 html 代码传递给它

$text= '<p class="red">A client is an application or system that accesses a service made available by a server. </p>';
ext_str_ireplace("cl", "<b>cl</b>", $text);

该函数当然会替换 "cl" 字符串

【问题讨论】:

  • 谢谢马里奥....我使用了下面答案中的解决方案,并从您的链接中添加了一些内容........+ 我添加了 utf8 标志,以确保安全..... return preg_replace('/('.$expression.')(?=[^>]*($1', $text);

标签: php regex string replace


【解决方案1】:
   function keywords($text, $words)
    {
        if (sizeof($words) == 1)
        {
            $expression = preg_quote($words[0]);
        }
        else
        {
            foreach ($words as $key => $word)
            {
                $words[$key] = preg_quote($word);
            }
            $expression = implode('|', $words);
        }   
        return preg_replace('/('.$expression.')(?=[^>]*(<|$))/iu', '<strong>$1</strong>', $text);
    }

用法:

keywords('Samsung', array('sa', 'ng'));

【讨论】:

  • 这如何解决我的问题?它不是 utf8 安全的 + 它不会跳过 html 标记
  • 好的,我使用了您的解决方案并添加了一个断言,正如 mario 在另一个答案中建议的那样..+ 我为 utf safe 添加了一个 u 标志............return preg_replace('/ ('.$expression.')(?=[^>]*($1', $text);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 2012-03-19
相关资源
最近更新 更多