PHP:检测文本或字符串中的单词

PHP:检测文本或字符串中的单词,php,Php,我有一篇很长的课文,我给了5个单词 我希望能够解析文本并突出显示这5个具有5种不同样式的单词 我正在使用php和js/jquery 实现这一目标的最佳实践是什么 一个str_替换('word'、'word'、$text'足够了吗? 注: 当这个词是大写或大写时该怎么办?避免使用JavaScript,因为并非所有浏览器都支持它,有些浏览器会关闭JS。 如果您有PHP,您就处于“理想”状态:使用它 如果使用str\u replace,则可以替换文本节点之外的字: <p id="word"&g

我有一篇很长的课文,我给了5个单词

我希望能够解析文本并突出显示这5个具有5种不同样式的单词

我正在使用php和js/jquery

实现这一目标的最佳实践是什么

一个str_替换('word'、'word'、$text'足够了吗?

注:
当这个词是大写或大写时该怎么办?

避免使用JavaScript,因为并非所有浏览器都支持它,有些浏览器会关闭JS。 如果您有PHP,您就处于“理想”状态:使用它

如果使用
str\u replace
,则可以替换文本节点之外的字:

 <p id="word"> ... </p>

这可能有问题

考虑使用HTML DOM库:
他们说,简单的HTMLDOM就像服务器端的jQuery

例如,如果您想将单词加粗

<?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>

?>

str\u replace也将匹配word1abc和MNword1,因此,uou应使用带有单词边界的preg\u 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);
?>

有关此函数的更多详细信息,请访问echo preg\u replace\u回调(数组映射)(函数($word){ 返回“/\b{$word}\b/i”; },数组('word','onion')),函数($matches){ 返回“{$matches[0]}”; }“单词洋葱洋葱abc”); //输出单词洋葱洋葱abc
str\u ireplace呢?我想我需要区分大小写,对吗?如果你需要像Word1,Word1这样的关键词。。是的,你想要str_ireplace你的字符串中有HTML吗?现在只需输入文本(幸运的是)如果我的关键字是“食盐”,而我的文本中有“盐”这个词,会发生什么?我怎样才能找到它呢?另外,如果我正在搜索单词“洋葱”,并且在给定的文本中有“洋葱”,只需更新正则表达式以包含单词边界,
/\b{$word}\b/I
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