dqq48152418 2011-11-26 08:49
浏览 40
已采纳

PHP:在一个字符串haystack中用一个html元素换(所有)针

for my autosuggest functionality I need to colorize the excerpts in suggestions...so..

if I search something like "sa" the suggester gives me thefolowing

Samsung satire sata e-sata ...

Now what I'd like from my function is that it highlights - wraps the "sa" needle (all occuracies) qith a desired html tag.

like Samsung satire sata e-sata

  • It should be utf8 safe
  • It should preserve the capitalization
  • it should ignore HTML

On the PHP site I found a function that does the replacement and keeps the capitalization... I modified it so it's utf8 friendly...

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; 
} 

It works great...like

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

untill I pass some html code into it

$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);

of course the function will replace the "cl" string in "

  • 写回答

1条回答 默认 最新

  • dongzenglin8292 2011-11-26 09:09
    关注
       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);
        }
    

    Usage:

    keywords('Samsung', array('sa', 'ng'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab计算中误差
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊