Remove tags from a string and then remove whitespace

There are many times when we need to create a product feed etc that doesn’t contain any html tags in the new string. strip_tags can clear out the tags but leaves your string unreadable in many instances.

Here’s a quick way to remove any tag and then remove the whitespace that remains so that your text in the string  is readable. 

If you only want a specific tag, just change the data inside the brackets.

// replace a specific tag with something else
$your_string = preg_replace('/<\/li>/', '.', $your_string);

// remove all tags from string and then remove any double spaces
$your_string = trim(preg_replace('/<[^>]*>/', ' ', $your_string));
$your_string = preg_replace('/\\s+/', ' ', $your_string);

// this removes &nbsp; &quot; etc
//$your_string = trim(preg_replace("/&#?[a-z0-9]+;/i","",your_string));

By replacing the tag with a space first, you’re able to go back and only change instances where double-spaces remain, keeping your string readable. Some instances of replacing tags you want a space replacement, while others you want to remove the space completely.

Leave a Reply