Manipulate HTML paragraphs in php

Possible duplicate:
Highlight keywords in paragraph

Here is another question for you. I have a little problem in php, and I thought before finding an unusual solution myself, perhaps a simpler and faster way to solve the problem.

Assuming I have a line containing HTML paragraph tags, such as:

$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 bites that contains some word "clues":

 $array=("Hello","nick", "help", "anyone", "solution") 

Now I would like to do the following: Print $string in the browser, but the words "key" must have a special format, for example. highlighted in bold or highlighted.

What makes me find this a little hard is that I want to keep the paragraphs as they are. In other words, I want the end result to look exactly like the original (including new lines / new paragraphs), but with some words bold

I thought I could use strip_tags to remove the <p> and </p> tags, and then split the returned string with spaces. To get an array of words. Then I output each word separately, checking if this word is contained in $array . If so, it will be displayed in bold.

Thus, I clearly lose the concept of new paragraphs, and all paragraphs will be merged into one.

Is there an easy way to fix this? For example, a way to get knowledge, for example, the word "Hello" begins in a new paragraph? Or is there something else I can do?

0
source share
3 answers

Just replace the words with formatted versions. The regular expression below supports case and replaces only complete words (so, for example, in the word "snicker" the word "nick" inside it is not replaced).

 preg_replace( '/\b('.implode( '|', $array ).')\b/i', '<em>$1</em>', $string ); 
+2
source

Why not just replace your keywords right away?

 $string = str_ireplace(array('hello', 'nick'), array('<strong>hello</strong>', '<strong>nick</strong>'), $string); 

(of course, the second array passed to the function will be created in advance)

0
source

use str_replace and replace the words with a bold tag around them

0
source

Source: https://habr.com/ru/post/1397119/


All Articles