php - 在到达字符串中的第一个 p 标签之前删除每个 li 标签

标签 php regex string domdocument

假设我有一个包含一些 HTML 的字符串。我想在到达第一个 p 标记之前删除每个 li 标记。

我如何实现这样的目标?

示例字符串:

$str = "<img src='something.png'/>some_text_here<li>needs_to_be_removed</li>
        <li>also_needs_to_be_removed</li>some_other_text<p>finally</p>more_text_here
        <li>this_should_not_be_removed</li>";`

需要删除前两个 li 标记。

最佳答案

这就是您所需要的。简单有效:

$mystring = "mystringwith<li>toberemovedstring</li><li>againremove</li><p>do not remove me</p>";//the string you provide
$findme   = '<li>';//the string you want to search in $mystring
$findpee = '<p>';//haha pee also where to end it
$pos = strpos($mystring, $findme);//first position of <li>
$pospee = strpos($mystring, $findpee);// then position of pee.. get it :)
//Then we remove it
$result=substr_replace ( $mystring ,"" , $pos, ($pospee-$pos));

    echo $result;

编辑:PHP 沙箱

http://sandbox.onlinephpfunctions.com/code/e534259e2312682a04b64c6e3aae1521422aacd2

您也可以在此处查看结果

关于php - 在到达字符串中的第一个 p 标签之前删除每个 li 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155542/

相关文章:

php - unset() 静态变量不起作用?

php - 自定义页面 Opencart 的分页

java regex 为什么这两个正则表达式不同

ruby - 用另一个字符替换 Ruby 中的字符

php - 使用 php Api 端点进行 Swift 网络调用

php - php 中的数据库随机函数?

.net - 从 [regex] 类型加速器表达式中捕获命名组的 PowerShell 语法是什么?

php - 如何删除空的 html 标签(包含空格和/或其 html 代码)

java - 如何在 Java 中移动数组中的位置?

ruby-on-rails - Ruby - 为什么这个构造返回零?