php strip_tags() .... 用空格替换标签而不是删除它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12824899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:18:12  来源:igfitidea点击:

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

php

提问by Jakob Alexander Eichler

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

你知道如何使用php用空格字符替换html标签吗?

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".

我得到的结果是“foobar”,但我需要将单词分开是“foo bar”。

回答by user40521

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

回答by Rezigned

Try this.

尝试这个。

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

回答by Ciantic

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

Preg 替换在大多数情况下都很好,只有一种极端情况,如此处所讨论的。这应该适用于两者:

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

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.

在 HTML 中任何标记之前添加一个空格都是有效的。它也有一些警告,比如如果你的文本出于某种原因有“<”并且不想在它之前添加空格。

回答by mgraph

try this:

尝试这个:

$str = '<h1>Foo</h1>bar';
echo trim(preg_replace('/<[^>]*>/', ' ', $str));

回答by tomazahlin

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.

我用来自 user40521 的例子帮助了我自己,但我用与 php 的 strip_tags 相同的 api 制作了一个函数,它不使用多个变量,而且还进行了修剪,因此从开始/结束中删除了一个空格。

/**
 * @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;
}

回答by Draguuun wra

preg_replace('#\<(.+?)\>#', ' ', $text);

Bit late with answer but try this one, basically selects everything inside <> including the tags.

回答晚了,但试试这个,基本上选择 <> 内的所有内容,包括标签。

回答by jmh

Something like this will work if you know that >won't be in any of your attributes.

如果您知道这>不会出现在您的任何属性中,这样的事情就会起作用。

preg_replace('/<[^>]+>/', ' ', 'hello<br>world');

preg_replace('/<[^>]+>/', ' ', 'hello<br>world');

回答by pmrotule

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

使用 Regex 解决方案preg_replace('/<[^>]*>/', ' ', $str),如果您有这样的事件属性,它将无法工作:

<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/", "<", $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!

希望能帮助到你!

回答by Baba

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;
}

回答by jwilcox09

First do a str_replace

首先做一个 str_replace

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