G
G
Gennady2020-07-31 18:26:18
PHP
Gennady, 2020-07-31 18:26:18

How to make a regulak for html-lists?

<p>There is some html code where tags can be different instead . For example:

<p>Some text</p>
<li>first list element</li>
<li>second list</li>
<p>Some text 2</p>
<p>Some text 3</p>
<li>first list element 2</li>
<li>second list element 2</li>
<h2>header 2</h2>


Help me compose a regular expression for preg_match (PHP) to select all the text from the first <li>to the last </li>in the list and wrap it in <ul> </ul>
That is, in fact, so that the output html code looks like:

<p>Some text</p>
<ul>
<li>first list element</li>
<li>second list</li>
</ul>
<p>Some text 2</p>
<p>Some text 3</p>
<ul>
<li>first list element 2</li>
<li>second list element 2</li>
</ul>
<h2>header 2</h2>


If it's easier to do it not through RegEx, it will be great)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FabiBoom, 2020-07-31
@FabiBoom

$str = "html";
$pattern = "/((<li>(.*?)<\/li>\s*)+)/s";

echo preg_replace($pattern, "<ul>$0</ul>", $str);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question