如何从字符串中删除所有标签?

Sha*_*deh 0 php regex security

我有一个包含一些标签的字符串,就像这样;

$str = '<i>this</i> <u class="anything">is</u> a <b>string</b>';
Run Code Online (Sandbox Code Playgroud)

我要这个:

$newstr = 'this is a string';
Run Code Online (Sandbox Code Playgroud)

其实我想选择之间的一切<>,然后用替换它''.我这样做的目标是防御CORSCSRF漏洞.我怎样才能做到这一点?

Rig*_*lly 8

使用该strip_tags功能将为您做到这一点

<?php
$str = '<i>this</i> <u class="anything">is</u> a <b>string</b>';
echo strip_tags($str);
Run Code Online (Sandbox Code Playgroud)

结果将是

this is a string
Run Code Online (Sandbox Code Playgroud)

这里还有REGEX版本:

echo preg_replace('/<[^>]*>/', '', $str); // output: this is a string
Run Code Online (Sandbox Code Playgroud)