问题
Possible Duplicate:
Highlight keywords in a paragraph
Here is another question for you. I have a small problem in php and I thought before find an extra-ordinary solution by myself there maybe an easier and faster way to solve the problem.
Assuming I have a string which contains HTML paragraph tags like:
$string="<p>Hello this is nick</p>
<p>i need some help over here</p>
<p></p><p>Does anyone know a solution</p>"
And an array of stings which contains some "clue" words:
$array=("Hello","nick", "help", "anyone", "solution")
I now would like to do the following:
Output the $string
in a browser but the "clue" words should have a special format e.g. being bold or highlighted.
What makes me find this a bit difficult is that I want to keep the paragraphs as there are. In other words I want the final output to look exactly as the original (including new lines/new paragraphs) but with some words bold
I thought I could use strip_tags to remove <p>
and </p>
tags and then split the returned string by spaces. So as to get an array of words. Then I would output each word individually by checking if that word is contained in the $array
. If yes, then it would be outputted with a bold style.
In this way I clearly lose the notion of new paragraphs and all the paragraphs will be merged in a single one.
Is there an easy way to fix that ? For example a way to have the knowledge that e.g. word "Hello" starts in a new paragraph? Or is there something else I can do?
回答1:
Just replace the words with formatted versions of themselves. The regex below maintains the case and replaces full words only (so that for example in the word "snicker" the word "nick" inside it isn't replaced).
preg_replace( '/\b('.implode( '|', $array ).')\b/i', '<em>$1</em>', $string );
回答2:
Why not just replace your clue words directly ?
$string = str_ireplace(array('hello', 'nick'), array('<strong>hello</strong>', '<strong>nick</strong>'), $string);
(of course the second array passed to the function would be generated beforehand)
回答3:
use str_replace and replace the words with bold tags around them
来源:https://stackoverflow.com/questions/9150156/manipulate-html-paragraphs-in-php