Using WordPress ‘clean_pre()’ PHP function

The clean_pre() WordPress PHP function ensures that the contents of a <pre>...</pre> HTML block are not converted into paragraphs or line breaks.

Usage

Let’s say you have a string which is within <pre> HTML tags and you want to ensure it remains as it is, not formatted into paragraphs or line breaks. You would use clean_pre() like this:

$my_text = "<pre>This is my text.</pre>";
$cleaned_text = clean_pre($my_text);

After running this code, $cleaned_text will hold the same value as $my_text, without any additional formatting.

Parameters

  • $matches (array|string) – Required. This can either be an array or string which represents the content you want to ensure remains unformatted.

More information

See WordPress Developer Resources: clean_pre()

This function is a part of the WordPress core and is used internally during the HTML rendering process.

Examples

Using clean_pre() with a string

The clean_pre() function can take a string as a parameter. This is useful when you have a single string of text that you want to keep unformatted.

$text = "<pre>Some unformatted text</pre>";
$clean_text = clean_pre($text);

The $clean_text variable will now contain the original string, unformatted.

Using clean_pre() with an array

The function can also take an array of strings, each string containing text within <pre> tags.

$texts = array("<pre>Text 1</pre>", "<pre>Text 2</pre>", "<pre>Text 3</pre>");
$clean_texts = array_map('clean_pre', $texts);

Now, $clean_texts will be an array with the original strings, none of them formatted.

Using clean_pre() in a loop

You can use the function within a loop to apply it to multiple strings.

$texts = array("<pre>Text 1</pre>", "<pre>Text 2</pre>", "<pre>Text 3</pre>");
foreach ($texts as $text) {
    $clean_text = clean_pre($text);
    // do something with $clean_text
}

In this case, each $clean_text inside the loop will hold an unformatted string.

Using clean_pre() with a multiline string

clean_pre() can handle multiline strings within <pre> tags as well.

$text = "<pre>Line 1\nLine 2\nLine 3</pre>";
$clean_text = clean_pre($text);

Here, $clean_text will contain the original string with the newline characters preserved.

Using clean_pre() with HTML tags inside <pre>

The function can handle other HTML tags within the <pre> tags, preserving them.

$text = "<pre><strong>Some unformatted text</strong></pre>";
$clean_text = clean_pre($text);

Now, $clean_text will contain the original string with the <strong> tags still intact.