Friday, February 24, 2012

Beautify an XML string in PHP (PCRE)

/*
 * Beautify an XML string.
 *
 * @param    string    Compressed/Unformatted XML string
 * @return   string    Formatted XML string
 */
function beautifyXmlString $xml )
{
    
// add marker linefeeds to aid the pretty-tokeniser
    // (adds a linefeed between all tag-end boundaries)
    
$xml preg_replace '/(>)(<)(\/*)/'"$1\n$2$3"$xml );

    
// now indent the tags
    
$token strtok $xml"\n" );
  
    
// holds formatted version as it is built
    
$result '';
  
    
// initial indent
    
$pad 0;
  
    
// returns from preg_matches()
    
$matches = array();

    
// scan each line and adjust indent based on opening/closing tags
    
while ( $token !== false )
    {  
        
// test for the various tag states

        // 1. open and closing tags on same line - no change
        
if ( preg_match '/.+<\/\w[^>]*>$/'$token$matches ) ) :
            
$indent 0;

        
// 2. closing tag - outdent now
        
elseif ( preg_match '/^<\/\w/'$token$matches ) ) :
            
$pad--;

        
// 3. opening tag - don't pad this one, only subsequent tags
        
elseif ( preg_match '/^<\w[^>]*[^\/]>.*$/',
                 
$token$matches ) ) :
            
$indent=1;

        
// 4. no indentation needed
        
else :
            
$indent 0;

        endif;

        
// pad the line with the required number of leading spaces
        
$line str_pad $tokenstrlen $token ) +
                
$pad"\t"STR_PAD_LEFT );
                 
        
// add to the cumulative result, with linefeed
        
$result .= $line "\n";
      
        
// get the next token
        
$token strtok "\n" );
      
        
// update the pad size for subsequent lines
        
$pad += $indent;
    }
    return 
$result;
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/
echo beautifyXmlString '<response><post><title>Damn in the World'.
                         
'</title></post></response>' );
/*
 +-----------+
 |  Output   |
 +-----------+
*/
/*
<response>
    <post>
        <title>Damn in the World</title>
    </post>
</response>
*/

Validate an IP Address ( PCRE )

/*
 Validation footprint:
 - First part must be > 0.

 - All parts will be <= 255.
 - No 0.0.0.0 match
 - 00, 000 are not allowed in pairs if
   first digit starts with 0. allowed for
   > 0 first digit.

 
Valid examples:
 - 12.255.99.2
 
- 115.92.255.66
 - 127.2.1.66:2082
 ...
*/

/**
 * Validate the MySQL Timestamp
 *
 * @author   Junaid Atari <mj.atari@gmail.com>
 * @version  1.0
 * @see      http://codesnap.blogspot.com/
 * @param    string  $ip   IP to validate
 * @return   bool    TRUE on valid | FALSE
 */

function isValidIp $ip )
{
    
/* PCRE Pattern written by Junaid Atari */
    
return !preg_match '/^([1-9]\d|1\d{0,2}|2[0-5]{2})\.('.
                         
'(0|1?\d{0,2}|2[0-5]{2})\.){2}(0|1?'.
                         
'\d{0,2}|2[0-5]{2})(\:\d{2,4})?$/',
                         (string) 
$ip )
            ? 
false
            
true;
}

/*
 +-----------+
 |  Example  |
 +-----------+
*/

var_dump isValidIp '127.0.0.1:8080' ) );

/*
 +-----------+
 |  Output   |
 +-----------+
*/

# Output: True