首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PHP从字符串中删除html元素

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

Stack Overflow用户
提问于 2011-09-23 21:24:02
回答 4查看 6.9K关注 0票数 4

我很难弄清楚怎么做,我有一个字符串看起来像这样…

代码语言:javascript
复制
    $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和正则表达式这样的东西来删除

代码语言:javascript
复制
<em>This is some example text This is some example text This is some example text</em>

所以我需要编写一些PHP代码来搜索打开的<em>和关闭的</em>,并删除其间的所有文本

希望有人能帮忙,谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-09-23 21:42:18

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

代码语言:javascript
复制
<?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);
    }

?>

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

票数 2
EN

Stack Overflow用户

发布于 2011-09-23 21:36:36

代码语言:javascript
复制
$text = preg_replace('/([\s\S]*)(<em>)([\s\S]*)(</em>)([\s\S]*)/', '$1$5', $text);
票数 4
EN

Stack Overflow用户

发布于 2011-09-23 21:41:07

使用strrpos查找第一个元素,然后查找最后一个元素。使用substr获取字符串的一部分。然后用原始字符串中的空字符串替换该子字符串。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7529636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档