Advertisement

This is about Me?

Do not read this

    Thanks To

    Related sites

    Community

    Syndication

    You can grab our news as an Atom feed.


    PHP: Keep HTML Tags Paired

    [14-Nov-2009]

    After applying substr to a string that contains HTML tags, usually I found that the result is broken because the closing tags are truncated.

    To prevent this, I have made a function that keep the closing tags remains and will not break the appearance of my website.

    Here is the function:

    HTML Pair Tags

    <?php</p>
    function 
    pair_tag($string) {
    $tags = Array('em','i','b','strong','div','span','p');
    //array of tags we will keep paired, you may add another
    foreach($tags as $tag) {

    $opentag     substr_count($string'<'.$tag);
    // I don't put > in the opentag in case they may have an attribute
    $closetag     substr_count($string'</'.$tag.'>');

    if(
    $opentag !== $closetag) {
    $return .= str_repeat('</'.$tag.'>', ($opentag-$closetag));
    }
    }
    return 
    $return;
    }
    <
    p>?>

    Usage/Example:

    Example

    <?php</p>
    $excerpt substr($string020);  //only display first 20 character
    $excerpt .= pair_tag($excerpt); // this will count any unclosed tags then close it.
    echo $excerpt// returns <p>This is my first pos</p>
    <p>?>

    Feedback and comment are welcome. Thanks

    Incoming search terms:


    News Archive