I just had this problem, but since strip_tags not enough to protect the values ββin the attribute tag, I will post my answer.
I use HTML Cleaner to remove all unwanted HTML elements and attributes. Open the console and run the following command to install it.
$ composer require ezyang/htmlpurifier "^4.6"
Then you can create your own Twig extension:
namespace AcmeBundle\Twig; class HTMLPurifierExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('html_purifier', array($this, 'purify'), array('is_safe' => array('html'))), ); } public function purify($text) { $elements = array( 'p', 'br', 'small', 'strong', 'b', 'em', 'i', 'strike', 'sub', 'sup', 'ins', 'del', 'ol', 'ul', 'li', 'h1', 'h2', 'h3', 'dl', 'dd', 'dt', 'pre', 'code', 'samp', 'kbd', 'q', 'blockquote', 'abbr', 'cite', 'table', 'thead', 'tbody', 'th', 'tr', 'td', 'a[href|target|rel|id]', 'img[src|title|alt|width|height|style]' ); $config = \HTMLPurifier_Config::createDefault(); $config->set('HTML.Allowed', implode(',', $elements)); $purifier = new \HTMLPurifier($config); return $purifier->purify($text); } public function getName() { return 'html_purifier'; } }
Open services.yml and register the extension as a service:
services: acme.html_purifier_extension: class: AcmeBundle\Twig\HTMLPurifierExtension public: false tags: - { name: twig.extension }
Now you can use it with
{{ post.content|markdown|html_purifier }}