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

前端 未结 10 987
日久生厌
日久生厌 2020-12-08 06:36

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

If I display

strip_tags(\'

Foo

bar\');

10条回答
  •  感动是毒
    2020-12-08 07:05

    With the Regex solution preg_replace('/<[^>]*>/', ' ', $str), it's not gonna work if you have event attributes like this:

    
    

    You need to do one more replacement:

    Hello!

    \">Hi.
    ". "Pleasehere."; $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!

提交回复
热议问题