从 php 字符串中删除所有 html 标记

我想显示数据库条目的前110个字符:

<?php echo substr($row_get_Business['business_description'],0,110) . "..."; ?>

但是上面的条目包含了客户端输入的 html 代码,所以它显示:

<p class="Body1"><strong><span style="text-decoration: underline;">Ref no:</span></strong> 30001<strong></stro...

显然不是什么好事。

我只是想去掉所有的 html 代码,所以我需要从 db 条目中删除 < 和 > 之间的所有内容。

有人知道吗?

264222 次浏览

Use PHP's strip_tags() function.

For example:

$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);




print($businessDesc);

use strip_tags

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);   //output Test paragraph. Other text


<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>

use this regex: /<[^<]+?>/g

$val = preg_replace('/<[^<]+?>/g', ' ', $row_get_Business['business_description']);


$businessDesc = substr(val,0,110);

from your example should stay: Ref no: 30001

Remove all HTML tags from PHP string with content!

Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';


echo strip_tags_content($srting);


function strip_tags_content($text) {


return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
    

}

Output:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

In laravel you can use following syntax

 @php
$description='<p>Rolling coverage</p><ul><li><a href="http://xys.com">Brexit deal: May admits she would have </a><br></li></ul></p>'
@endphp
\{\{  strip_tags($description)}}

For my this is best solution.

function strip_tags_content($string) {
// ----- remove HTML TAGs -----
$string = preg_replace ('/<[^>]*>/', ' ', $string);
// ----- remove control characters -----
$string = str_replace("\r", '', $string);
$string = str_replace("\n", ' ', $string);
$string = str_replace("\t", ' ', $string);
// ----- remove multiple spaces -----
$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;


}

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

Or if you have a content coming from the database;

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

$string = <p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting enter code here;
$tags = array("p", "i");


echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);

Try this

Strip the string from HTML tags:

<?php
echo strip_tags("Hello <b>world!</b>");
?>

Strip the string from HTML tags, but allow tags to be used:

<?php
echo strip_tags("Hello <b><i>world!</i></b>","<i>");
?>