strip_tags() .... replace tags by space rather than deleting them

Do you know how to replace html tags with a space character using php?

If I display

strip_tags('<h1>Foo</h1>bar');

I get as result "foobar" but what I need to keep words separate is "foo bar".


Solution 1:

$string      = '<h1>Foo</h1>bar';
$spaceString = str_replace( '<', ' <',$string );
$doubleSpace = strip_tags( $spaceString );
$singleSpace = str_replace( '  ', ' ', $doubleSpace );

Solution 2:

Try this.

preg_replace('#<[^>]+>#', ' ', '<h1>Foo</h1>bar');

Solution 3:

Preg replace is fine most of the cases, there is that one corner case, as discussed here. This should work for both:

strip_tags(str_replace('<', ' <', $str));

Adding a space before any tag is valid in HTML. It too has some caveats like if your text has "<" for some reason and don't want to add space before it.

Solution 4:

I helped my self with example from user40521, but I made a function with same api like php's strip_tags, it does not use multiple variables, and it also makes a trim, so a single whitespace is removed from start / end.

/**
 * @param string $string
 * @param string|null $allowable_tags
 * @return string
 */
function strip_tags_with_whitespace($string, $allowable_tags = null)
{
    $string = str_replace('<', ' <', $string);
    $string = strip_tags($string, $allowable_tags);
    $string = str_replace('  ', ' ', $string);
    $string = trim($string);

    return $string;
}