Skip to content

Instantly share code, notes, and snippets.

@zmcghee
Last active July 6, 2016 21:30
Show Gist options
  • Save zmcghee/56cb54170cae61654f330e6ca3ce094b to your computer and use it in GitHub Desktop.
Save zmcghee/56cb54170cae61654f330e6ca3ce094b to your computer and use it in GitHub Desktop.
Repair open HTML tags in a PHP string
<?php
/**
* Find unclosed HTML tags in a string and repair them.
* For example:
* $str = '<p>Hi, I\'m <b><a href="mailto:za ... ">Zack</a>';
* echo close_open_html_tags( $str );
* would show '<p>Hi, I\'m <b><a href="mailto:za ... ">Zack</a></b></p>'
*/
function close_open_html_tags( $str ) {
// Find all open tags
preg_match_all( '@<(?P<elem>[a-z]+)[ |>]@Ui', $str, $open_tags );
preg_match_all( '@</(?P<elem>[a-z]+)[ |>]@Ui', $str, $close_tags );
$open_tags = $open_tags['elem'];
$close_tags = $close_tags['elem'];
// Work our way out in the order they would be closed
$open_tags = array_reverse( $open_tags );
for( $i=0; $i<count($close_tags); $i++ ) {
if( $open_tags[$i] == $close_tags[$i] ) {
// This tag was closed and in the proper order
unset( $open_tags[$i] );
}
}
// Close all open tags
foreach( $open_tags as $open_tag ) {
$str .= "</$open_tag>";
}
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment