Php – How to balance tags with PHP

PHP

In the string below, I want to replace <!--more--> with some text, FOOBAR, then truncate the string.

<p>The quick <a href="/">brown</a> fox jumps <!--more-->
over the <a href="/">lazy</a> dog.</p>

I've got to this point:

<p>The quick <a href="/">brown</a> fox jumps FOOBAR

… but as you can see, the <p> tag is not closed. Any ideas on how I could consistently balance the tags? I am pretty new to PHP.

The array I am working with looks like this:

array(2) {
  [0]=>
  string(50) "<p>The quick <a href="/">brown</a> fox jumps "
  [1]=>
  string(45) " over the <a href="/">lazy</a> dog.</p>"
}

Best Answer

You can use the wordpress force_balance_tags function. The implementation lives here :-

http://core.trac.wordpress.org/browser/trunk/wp-includes/formatting.php

This is a standalone function that you can just copy+paste in your code.

function force_balance_tags( $text ) {

Usage is simple

$bad_text = "<div> <p> some text </p> " ;

echo force_balance_tags($bad_text);

since this is part of wordpress, it is tried and tested and better than adHoc regex macthing solutions.