Part of the EllisLab Network
   
 
[OPTIMIZATION] form_prep() + xml_convert() + convert_xml()
Posted: 13 May 2007 03:31 PM   [ Ignore ]  
Lab Assistant
Avatar
RankRank
Total Posts:  248
Joined  02-10-2007

system/helpers/xml_helper.php - line 37


BEFORE: 10000 iterations take about 0.4759 seconds

function xml_convert($str)
{
    $temp
= '__TEMP_AMPERSANDS__';

    
// Replace entities to temporary markers so that
    // ampersands won't get messed up
    
$str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
    
$str = preg_replace("/&(\w+);/",  "$temp\\1;", $str);
    
    
$str = str_replace(array("&","<",">","\"", "'", "-"),
                       array("&amp;", "& lt;", "& gt;", "&quot;", "&#39;", "&#45;"),
                       $str);

    // Decode the temp markers back to entities        
    $str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
    $str = preg_replace("/$temp(\w+);/","&\\1;", $str);
        
    return $str;
}


AFTER: 10000 iterations take about 0.1962 seconds

function xml_convert_geert($str) {
    
    
// Convert ampersands to entities only if they're not part of an existing entity
    
$str = preg_replace('/&(?!(#\d+|[a-z]+);)/i', '&amp;', $str);
    
    
// Convert: < > ' " -
    
$str = str_replace(
        array(
'<', '>', '\'', '"', '-'),
        array('& lt;', '& gt;', '&#39;', '&quot;', '&#45;'),
        $str
    );
    
    return $str;
}


Note that the spaces in & lt; and & gt; should be removed. If I didn’t space these entities out, the forum converts them to the actual < and > characters.


My optimized version of this function is a lot faster and cleaner, right?

Please copy this optimization to the following locations as well:
- system/helpers/form_helper.php > form_prep() - line 340
- system/libraries/Trackback.php > convert_xml() - line 406

 Signature 

Kohana rocks!

Profile
 
 
Posted: 14 May 2007 08:11 AM   [ Ignore ]   [ # 1 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  248
Joined  02-10-2007

A tiny update, made the inner parentheses non-capturing.

$str = preg_replace('/&(?!(?:#\d+|[a-z]+);)/i', '&amp;', $str); // new
$str = preg_replace('/&(?!(#\d+|[a-z]+);)/i', '&amp;', $str); // old

 Signature 

Kohana rocks!

Profile
 
 
Posted: 14 May 2007 08:30 PM   [ Ignore ]   [ # 2 ]  
Lab Assistant
RankRank
Total Posts:  144
Joined  09-08-2006

very nice…

Profile
 
 
   
 
 
‹‹ Problem with server      Problem with ODBC ››
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 719, on June 06, 2008 10:16 AM
Total Registered Members: 64455 Total Logged-in Users: 26
Total Topics: 80962 Total Anonymous Users: 1
Total Replies: 435698 Total Guests: 182
Total Posts: 516660    
Members ( View Memberlist )