First of all, thanks. I took your code and did some changes.
Here is the new code:
Code: Select all
<?php
$bad_parse = "if( \$var = \$var )
{
echo 'some';
}
else
{
echo 'other';
}";
echo block_parsing_example( $bad_parse );
function block_parsing_example( $input )
{
// Matches if, else, elseif, else if blocks
// - Doesn't work with functions in the condition
// - Doesn't work with comments immediately after condition
// - Doesn't work with } in strings, comments, or nested blocks
// - Doesn't work with blocks without {}
// - Doesn't work with multiple whitespace characters in strings
if ( preg_match_all('/((if|else\s*if)\s*\([^\)]+\)|else)\s*\{[^\}]*\}/i', $input, $blocks) )
{
foreach ($blocks[0] as $block)
{
//$output .= '<pre class="b">';
$closing_tag = '';
// Matches "elseif" or "else if" condition
if (preg_match('/else\s*if\s*\([^\)]+\)/i', $block, $condition))
{
// Cleans condition statement
// 1. Adds <elseif="
// 2. Removes elseif(
// 3. Removes white space around condition
// 4. Removes closing )
// 5. Adds >
$output = '<elseif="'.str_replace('"', '\"', trim(substr(preg_replace('/else\s*if\s*\(/i', '', $condition[0]), 0, -1))).'">';
$closing_tag = '</elseif>';
}
// Matches "if" condition
else if (preg_match('/if\s*\([^\)]+\)/i', $block, $condition))
{
// Cleans condition statement
// 1. Adds <if="
// 2. Removes if(
// 3. Removes whitespace characters around condition
// 4. Removes closing )
// 5. Adds >
$output = '<if="'.str_replace('"', '\"', trim(substr(preg_replace('/if\s*\(/i', '', $condition[0]), 0, -1))).'">';
$closing_tag = '</if>';
}
// Matches "else" condition
else
{
// 1. Adds <else>
$output = '<else>';
$closing_tag = '</else>';
}
// Cleans statements in block
// 1. Removes condition and closing brace
// 2. Escapes double quotes
// 3. Converts multiple whitespace characters to a single space
// 4. Trims leading and trailing whitespace characters
//$content = trim(preg_replace('/(\h*\v\h*)|\h+/', ' ', str_replace('"', '\"', substr(preg_replace('/((if|else\s*if)\s*\([^\)]+\)|else)\s*\{/i', '', $block), 0, -1))));
//$content .= preg_replace("#(if|else|else\s*if)+(\s|\n)*{(.+?)(\s|\n)*}#", $output. "\\1". $closing_tag, $block);
$in_state .= preg_replace("#(if|else\s*if|else)\((.+?)\)+(\s|\n)*[\{]*(\s|\n)*(.+?)(\s|\n)*[\}]*#i", "\\5", $block);
$content .= str_replace($block, $output. $in_state. $closing_tag, $block);
//$content .= $closing_tag;
//$output .= "</pre>\n";
}
}
return $content;
}
?>
Returns:
<if="$var = $var">echo 'some'; }</if><else>echo 'some'; }else { echo 'other'; }</else>
How can I fix it? By the way, I'll be glad if you could get rid of the <?php and ?> (by regex of course)