Search code examples
htmlregexphp4

PHP: Inject iframe right after body tag


I would like to place an iframe right below the start of the body tag. This has some issues since the body tag can have various attributes and odd whitespace. My guess is this will will require regular expressions to do correctly.

EDIT: This solution has to work with php 4 & performance is a concern of mine. It's for this http://drupal.org/node/586210#comment-2567398


Solution

  • Both PHP 4 and PHP 5 should be happy with preg_split():

    /* split the string contained in $html in three parts: 
     * everything before the <body> tag
     * the body tag with any attributes in it
     * everything following the body tag
     */
    $matches = preg_split('/(<body.*?>)/i', $html, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
    
    /* assemble the HTML output back with the iframe code in it */
    $injectedHTML = $matches[0] . $matches[1] . $iframeCode . $matches[2];