Home » Php » textarea – Php tidy and text areas

textarea – Php tidy and text areas

Posted by: admin July 12, 2020 Leave a comment


I am using tidy to clean up and format the output of HTML generated by the twig template engine.

I am using the following configuration for tidy:

$config = array('indent' => TRUE, 'output-html' => TRUE, 'wrap' => 0);

Everything works nice and well, except when we get to textareas.

Here’s the uncleaned fragment:

<textarea id="words"
         rows="10"       cols="50"                  >sdfds</textarea>

While the formatting is very messy, the correct value is outputted in the text area: ‘sdfds’ without any whitespace before or after.

This is the cleaned format after using tidy:

                <textarea id="words" name="words" rows="10" cols="50" title="prompt">

As can be seen, the markup is much neater now, but tidy has introduced a linebreak after ‘sdfds’, which means that the cursor is now pointing at the line after ‘sdfds’ when viewed in the browser.

This is rather annoying, and I am not sure how to go about dealing with this. I would still want to have the textarea tag cleaned up, but I would prefer it to be formatted like so:

<textarea id="words" name="words" rows="10" cols="50" title="prompt">sdfds</textarea>

Has anyone dealt with this issue before? If so, How can I get tidy to not introduce those whitespaces for the textarea tag?

How to&Answers:

If sdfds is outputed with php you will need to add another config option.

 $config = array('indent' => TRUE, 'output-html' => TRUE, 'wrap' => 0, 'wrap-php' => 0);

Wrap only worries about html and any php statements are treated as a new line. For more information on config options you can visit: http://tidy.sourceforge.net/docs/quickref.html


When you use indent => true you will get messed up texareas with tidy. It gets to tidy because even the textareas value is indented. If you want your textareas to appear correct you could just set indent => false. This will tidy up your HTML, but will also leave your textarea with the same value after applying tidy. I have seen there are some patches which solves the problem, but then you should compile tidy yourself. You could also do this with PHP but then you are tidying up tidy.


Tidy can be rally a “messy” sometimes and needs further refinement with rexep, here is a workaround that will put the cursor on the same line in the final output, so the usability doesn’t suffer. Just run your tidied html trough:

$subject = preg_replace('%(\r\n|\n)(?=</textarea>)%sim', '', $subject);


Just use trim function for text area. And you will get what you are looking for