PHP: Detect words in text or string
I have a long text, and I have 5 words given.
I'd like to be able to parse the text and highlight those 5 words with 5 different styles.
I'm working with php and js/jquery.
what's the best practice to accomplish this?
is enough a str_replace('word','<span style1 >word</span>', $开发者_如何学运维text)?
NOTE: what about when the word is uppercase or capitalized?
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
For example if you wanted to bold the words.
<?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>
?>
Avoid JavaScript, because not all browsers support it and some turn JS off. If you have PHP, you are in the "ideal" situation: use it.
If you use str_replace
, you can replace out words outside of text nodes:
<p id="word"> ... </p>
Which may be problematic.
Consider using a HTML DOM library: http://simplehtmldom.sourceforge.net/#fragment-12 They said, Simple HTML DOM is like a jQuery on the server-side.
str_replace will also match word1abc and MNword1 therefore uou should use preg_replace function with word boundry:
<?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);
?>
For more details on this function please visit preg-replace manual
精彩评论