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".
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".
$string = '<h1>Foo</h1>bar';
$spaceString = str_replace( '<', ' <',$string );
$doubleSpace = strip_tags( $spaceString );
$singleSpace = str_replace( ' ', ' ', $doubleSpace );
$doubleSpace = strip_tags( $spaceString );
with $doubleSpace = preg_replace('/\s\s+/', ' ', $spaceString);
so that it replaces any combination of space repetition into a single space.
Jan 22, 2015 at 16:55
str_replace( ' ', ' ', strip_tags( str_replace( '<', ' <','<h1>Foo</h1>bar' ) )
)
Dec 30, 2015 at 17:18
Try this.
preg_replace('#<[^>]+>#', ' ', '<h1>Foo</h1>bar');
<button onclick="document.getElementById('alert').innerHTML='<strong>MESSAGE</strong>';" />
. Do you have something else in mind?
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.
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;
}
$string = preg_replace('/\s+/', ' ', $string);
Oct 6, 2020 at 12:17
preg_replace('#\<(.+?)\>#', ' ', $text);
Bit late with answer but try this one, basically selects everything inside <> including the tags.
try this:
$str = '<h1>Foo</h1>bar';
echo trim(preg_replace('/<[^>]*>/', ' ', $str));
strip_tags
at that point? Shouldn't the RegEx take care of them all?
Oct 10, 2012 at 17:35
<button onclick="document.getElementById('alert').innerHTML='<strong>MESSAGE</strong>';">
, strip_tags will do the job, Regex won't.
Something like this will work if you know that >
won't be in any of your attributes.
preg_replace('/<[^>]+>/', ' ', 'hello<br>world');
With the Regex solution preg_replace('/<[^>]*>/', ' ', $str)
, it's not gonna work if you have event attributes like this:
<button onclick="document.getElementById('alert').innerHTML='<strong>MESSAGE</strong>';">
click</button>
You need to do one more replacement:
<?php
$str =
"<div data-contents=\"<p>Hello!</p>\">Hi.</div>".
"Please<button onclick=\"document.getElementById('alert').innerHTML='".
"<strong>MESSAGE</strong>';\">click</button>here.";
$event =
"onafterprint|onbeforeprint|onbeforeunload|onerror|onhaschange|onload|onmessage|".
"onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onstorage|onunload|".
"onblur|onchange|oncontextmenu|onfocus|oninput|oninvalid|onreset|onselect|onsubmit|".
"onkeydown|onkeypress|onkeyup|onclick|ondblclick|ondrag|ondragend|ondragenter|".
"ondragleave|ondragover|ondragstart|ondrop|onmousedown|onmouseenter|onmousemove|".
"onmouseleave|onmouseout|onmouseover|onmouseup|onscroll|onabort|oncanplay|".
"oncanplaythrough|oncuechange|ondurationchange|onemptied|onended|onerror|".
"onloadeddata|onloadedmetadata|onloadstart|onpause|onplay|onplaying|onprogress|".
"onratechange|onseeked|onseeking|onstalled|onsuspend|ontimeupdate|onvolumechange|".
"onwaiting|data-[^=]+";
$str = preg_replace("/<([^>]+)(".$event.")=(\"|')(?:(?!\\3).)+\\3/", "<$1", $str);
$str = preg_replace("/<[^>]*>/", " ", $str);
echo $str;
// with only strip_tags:
// Hi.Pleaseclickhere.
// with event and data attributes removal + regex tags removal:
// Hi. Please click here.
// with only regex tags removal:
// Hello! ">Hi. Please MESSAGE ';">click here.
?>
Hope it helps!
You can try
$str = '<h1>Foo</h1>bar';
var_dump(replaceTag($str,array("h1"=>"div")));
Output
string '<div>Foo</div>bar' (length=17)
Function Used
function replaceTag($str,$tags) {
foreach ( $tags as $old => $new )
$str = preg_replace("~<(/)?$old>~", "<\\1$new>", $str);
return $str;
}
If you rely on strip_tags for these embedded attributes then that will work. Try this ...
function strip_tags_with_spacer(string $html, string $allowedTags) {
$allowedTagsArr=explode("<",strtolower(str_replace(">", "",$allowedTags)));
$tags=[];
$dom = new DOMDocument();
$dom->loadHTML($html);
$selector = new DOMXPath($dom);
$elements = $dom->getElementsByTagName('*');
foreach($elements as $child) $tags[$child->tagName]=$child->tagName;
foreach ( $tags as $tag ) {
if ( !in_array(strtolower($tag), $allowedTagsArr)) {
if ( in_array(strtolower($tag), ["p", "div", "h1", "h2", "h3", "h4", "pre", "body", "html", "form", "ul", "ol", "li", "table", "th", "td", "blockquote"])) $gap=" ";
else $gap="";
//echo "\nreplacing [$tag] with [$gap][$tag]";
$html = str_ireplace("</$tag", "$gap</$tag", $html);
}
}
return strip_tags($html, $allowedTags);
}
$result=strip_tags_with_spacer($str,"<button><b><u><i>");
See http://sandbox.onlinephpfunctions.com/code/37299b1476dccb0631d404a073cf1c88f1cb7d2b for a
First do a str_replace
$string = '<h1>Foo</h1>bar'
strip_tags(str_replace('</h1>', ' ',$string));
strip_tags()
>
withstr_replace()
and the extra spaces will get collapsed on screen, but that of course won't work if you have fussy markup likea word wi<span class='othercolor'>th spec</span>ial colors inside