user2145985
user2145985

Reputation:

Parse HTML text into a flat array of whole tags

I would like to split/explode a string in PHP. The string looks like this:

<strong>Label</strong><p>Value</p>

With this result:

array(
    '<strong>Label</strong>',
    '<p>Value</p>'
)

How can I do this?

Upvotes: 0

Views: 648

Answers (5)

splash21
splash21

Reputation: 809

This should do the trick;

$string = "<strong>Label</strong><p>Value</p>";
$array = explode("\t", str_replace("><", ">\t<", $string));

Upvotes: 0

Pitchinnate
Pitchinnate

Reputation: 7556

You can do it like this:

$string = "<strong>Label</strong><p>Value</p>";
$pos = strpos($string,'<p>');
$array = array();
$array[] = substr($string, 0,$pos);
$array[] = substr($string,$pos);

Or using preg_match:

preg_match('%(.*g>)(.*)%',$string,$array);
//$array[1] = '<strong>Label</strong>'
//$array[2] = '<p>Value</p>'

Upvotes: 2

Krista K
Krista K

Reputation: 21851

Isn't this always faster than preg functions?

<?php
$str = "<strong>Label</strong><p>Value</p>";
$str = explode( "g><p", $str );
$str = implode( "g>~<p", $str);
$str = explode( "~", $str );

And be warned: tags can get nested and the logic gets difficult.

Upvotes: 1

Julio
Julio

Reputation: 2290

That's not how split works. You need to use preg_split with the PREG_SPLIT_DELIM_CAPTURE flag.

Upvotes: 0

Adam Plocher
Adam Plocher

Reputation: 14233

You're not going to be able to achieve that with explode, without doing something kinda hacky like:

$str = "<strong>Label</strong><p>Value</p>";
$strExp = explode("<p>", $str);
$strExp[1] = "<p>" . $strExp[1];

I would recommend using regular expressions instead.

Upvotes: 0

Related Questions