使用PHP从字符串中删除html元素

2022-03-22 00:00:00 string regex php preg-replace

我在计算如何执行此操作时遇到问题,我有一个类似于以下内容的字符串.

    $text = "<p>This is some example text This is some example text This is some example text</p>
             <p><em>This is some example text This is some example text This is some example text</em></p>
             <p>This is some example text This is some example text This is some example text</p>";

我基本上想使用preg_repalce和regex之类的东西来删除

<em>This is some example text This is some example text This is some example text</em>

因此,我需要编写一些PHP代码来搜索开始<em>和结束</em>,并删除其间的所有文本

希望有人能帮忙, 谢谢。


解决方案

如果您对非正则表达式解决方案感兴趣,也可以:

<?php
    $text = "<p>This is some example text This is some example text This is some example text</p>
             <p><em>This is some example text This is some example text This is some example text</em></p>
             <p>This is some example text This is some example text This is some example text</p>";


    $emStartPos = strpos($text,"<em>");
    $emEndPos = strpos($text,"</em>");

    if ($emStartPos && $emEndPos) {
        $emEndPos += 5; //remove <em> tag aswell
        $len = $emEndPos - $emStartPos;

        $text = substr_replace($text, '', $emStartPos, $len);
    }

?>

这将删除标记之间的所有内容。

相关文章