Skip to content
Advertisement

split each HTML tag into new line using PHP

I’m going to split each HTML tag into a new line. This is my source:

<p><a href="http://www.example.com">Example Link</a></p>
<div class="text-center"><a href="http://www.example2.com">Example2 Link</a></div>

And I’m gonna have it like this:

<p>
<a href="http://www.example.com">Example Link</a>
</p>
<div class="text-center">
<a href="http://www.example2.com">Example2 Link</a>
</div>

or like this:

<p>
<a href="http://www.example.com">
Example Link
</a>
</p>
<div class="text-center">
<a href="http://www.example2.com">
Example2 Link
</a>
</div>

And this is what I’ve done:

$myfile = fopen("html.txt", "r");
for ($i = 0; $i < 1; $i++) {
$line = fgets($myfile);
var_dump(preg_split('/(>)/', $line, 0, PREG_SPLIT_DELIM_CAPTURE));
}

and this is the output with put each “>” in a separate line (array member).

array(9) {
  [0]=>
  string(2) "<p"
  [1]=>
  string(1) ">"
  [2]=>
  string(32) "<a href="http://www.example.com""
  [3]=>
  string(1) ">"
  [4]=>
  string(15) "Example Link</a"
  [5]=>
  string(1) ">"
  [6]=>
  string(3) "</p"
  [7]=>
  string(1) ">"
  [8]=>
  string(2) "
"
}

Advertisement

Answer

Instead of using a regex and splitting your source into an array, you could use the str_replace() function to replace > / < with a > / < and a newline. See PHP documentation

This should work fine:

$formatted = str_replace([">", "<"], [">n", "n<"], $x);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement