Подборка регулярных выражений для удаления HTML тегов и атрибутов.
Удаление <style>...</style>
.
$text = '<p>Текст <style color="#fff">стиль</style> текст</p>';
echo preg_replace('/\s?<style[^>]*?>.*?<\/style>\s?/si', ' ', $text);
Результат:
<p>Текст текст</p>
По аналогии удаление тегов <p>
, <div>
и <script>
:
$text = '<p class="text" style="margin: 0 0 0 0;" id="fid-123">текст</p>';
// Удалить class
echo preg_replace('/\s?class=["][^"]*"\s?/i', ' ', $text);
// Удалить style
echo preg_replace('/\s?style=["][^"]*"\s?/i', ' ', $text);
// Удалить id
echo preg_replace('/\s?id=["][^"]*"\s?/i', ' ', $text);
Результат:
<p style="margin: 0 0 0 0;" id="fid-123">текст</p>
<p class="text" id="fid-123">текст</p>
<p class="text" style="margin: 0 0 0 0;" >текст</p>
Удалить все атрибуты у тегов:
$text = '<p style="margin: 0 0 0 0;" class="text" id="fid-123">текст</p>';
echo preg_replace("/(<[a-z]).*?(>)/i", '\\1\\2', $text);
Результат:
<p>текст</p>
Удалить атрибуты только у определенных HTML тегов:
$text = preg_replace("/(<p).*?(>)/i", '\\1\\2', $text);
$text = preg_replace("/(<div).*?(>)/i", '\\1\\2', $text);
Регулярные выражения удаляют теги <p>
и <div>
, но оставляет их содержание.
$text = '
<table>
<tr>
<td>text 1</td>
<td><p>text 2</p></td>
<td><div>text 3</div></td>
</tr>
</table>';
// Удаление <p>
$text = preg_replace('/(<td[^>]*>)(.*)(<p[^>]*>)(.*)(<\/p>)(.*)(<\/td>)/i', '\\1\\2\\4\\6\\7', $text);
// Удаление <div>
$text = preg_replace('/(<td[^>]*>)(.*)(<div[^>]*>)(.*)(<\/div>)(.*)(<\/td>)/i', '\\1\\2\\4\\6\\7', $text);
print_r($text);
Результат:
<table>
<tr>
<td>text 1</td>
<td>text 2</td>
<td>text 3</td>
</tr>
</table>