Using PHP to remove a html element from a string(使用PHP从字符串中删除html元素)

本文介绍了使用PHP从字符串中删除html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

?>

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

这篇关于使用PHP从字符串中删除html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!