[英]PHP: Detect words in text or string
我有很长的文字,并且给出了5个字。
我希望能够解析文本并以5种不同样式突出显示这5个单词。
我正在使用php和js / jquery。
什么是实现这一目标的最佳实践?
一个str_replace('word','<span style1 >word</span>', $text)?
是否足够str_replace('word','<span style1 >word</span>', $text)?
注意:当单词为大写或大写字母时该怎么办?
echo preg_replace_callback(array_map(function($word){
return "/\b{$word}\b/i";
}, array('word', 'onion')), function($matches){
return "<em>{$matches[0]}</em>";
}, 'word woRd onions onion abc');
// outputs <em>word</em> <em>woRd</em> onions <em>onion</em> abc
例如,如果您想将单词加粗。
<?php
$words = array('word1', 'word2', 'word3');
$replacement = array();
foreach($words as $word){
$replacement[] = "<strong>" . $word . "</strong>";
}
$new_str = str_replace($words, $replacement, "I really like word1 and word2 and word3");
echo $new_str;
// prints I really like <strong>word1</strong> and <strong>word2</strong> and <strong>word3</strong>
?>
避免使用JavaScript,因为并非所有浏览器都支持JavaScript,并且有些浏览器会关闭JS。 如果您拥有PHP,那么您将处于“理想”状态:请使用它。
如果使用str_replace
,则可以替换文本节点之外的单词:
<p id="word"> ... </p>
这可能是有问题的。
考虑使用HTML DOM库: http : //simplehtmldom.sourceforge.net/#fragment-12他们说,简单HTML DOM就像服务器端的jQuery。
str_replace也将匹配word1abc和MNword1,因此,您应该将preg_replace函数与单词绑定一起使用:
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/\bword1\b/';
$patterns[1] = '/\bword2\b/';
$patterns[2] = '/\bword3\b/';
$patterns[3] = '/\bword4\b/';
$patterns[4] = '/\bword5\b/';
$replacements = array();
$replacements[0] = '<span style1>word1</span>';
$replacements[1] = '<span style2>word2</span>';
$replacements[2] = '<span style3>word3</span>';
$replacements[3] = '<span style4>word4</span>';
$replacements[4] = '<span style5>word5</span>';
echo preg_replace($patterns, $replacements, $string);
?>
有关此功能的更多详细信息,请访问preg-replace手册
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.