Jun 13

To automaticaly cleanup and repair xhtml code (ex. from textarea or input tag) use Tidy extesnion for PHP.
Sample broken code which can be fixed

<p>ala <b> ma kota & psa<br />Lorem ipsum

to valid XHTML:

<p>ala <b> ma kota &amp; psa<br />Lorem ipsum</b></p>

Simple function which repair wrong code:

/**
* Use php tidy extension to cleanup code.
*
* @param string $text
* @return string
* @author Rafal Zelazko <rafal [at]zelazko.info>
*/
function tidy($text)
{
if (function_exists('tidy_parse_string'))
{
$config = array('indent' => true,
'output-xhtml' => true,
'wrap' => 200);
$tidy = tidy_parse_string($text, $config, 'UTF8');
$body = tidy_get_body($tidy);
$text = preg_replace('/< \/?body[^>]*>/im', '', $body->value);
return trim($text);
}

trigger_error('tidy extension not found', E_USER_WARNING);
return $text;
}

I wrote Symfony Framework Plugin – http://www.symfony-project.org/plugins/sfTidyPlugin with TidyHelper which implements it.

written by rzelazko \\ tags: , , , , , , ,

Leave a Reply