Insert string into array

It may be easy to do, but I cannot create the correct regular expression.

Say I have this line

$string = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" /><h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p><h2>Header 3</h2><p>ajdas ahkds hakd</p>';

And I need it as if

$array[0] = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" />';
$array[1] = '<h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p>';
$array[2] = '<h2>Header 3</h2><p>ajdas ahkds hakd</p>';

... and so on, if my line contains more of these H2 blocks.

So, the split point is in H2, and it needs to save the HTML tags. Any pointers?

+3
source share
3 answers

Use preg_split()with a positive look at the opening tag:

print_r(preg_split('/(?=<h2>)/', $string, -1, PREG_SPLIT_NO_EMPTY));

A positive lookahead simply tells the regex parser to split the text surrounding <h2>but not eliminate the tag. If you split by /<h2>/, the tag will disappear, as if you were split using explode().

+4
$result = split('(?=<h2>)', $string);

$result = preg_split('/(?=<h2>)/', $string);
+1
$string = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" /><h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p><h2>Header 3</h2><p>ajdas ahkds hakd</p>';

$matches    = split('<h2>', $string);

print_r($matches);

PHP 5.3.0.

0

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


All Articles