Skip to main content
1 of 3
usernameabc
  • 2.8k
  • 5
  • 48
  • 98

Strip html tags in preprocess hook

We have a mytheme.theme file that has a mytheme_preprocess_node(&$variables) function. Within this preprocess hook, we would like to remove all HTML tags within a formatted (long) field. The goal is to do without using striptags within the node--page.html.twig template.

How can we do this securely without using striptags in a twig template?

Here is what we tried, but cannot find how to do it using mytheme_preprocess_node hook.

mytheme.theme

function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];
  $field_value = $node->get('body')->first()->getValue()['value'];
  ksm($field_value);
  // cannot find way to remove `html` tags
}

output of ksm($field_value)

"& lt;p & gt;When looking at & lt;a href="https://www.example.com/some-path/"& gt;article trends& lt;/a& gt; over time, attacks are cyclical in nature. Attackers develop new attack types and vectors, which are used to launch a new wave of attacks. As defenders become more proficient in stopping these new attacks, the attackers develop new types of attacks and the cycle repeats itself.</p& gt;

In order to properly display the output, I had to a space between & and lt characters above because StackExchange will convert those to proper tags. Within the ksm statement there is no space.

usernameabc
  • 2.8k
  • 5
  • 48
  • 98