使用 PHP 仅去除字符串中的第一个 <p> 和最后一个 </p>

Use PHP to strip 1st <p> and last </p> only in a string

我找到了很多 preg_replace 解决这个问题的方法,最接近的是这个:

$string = preg_replace('/<p[^>]*>(.*)<\/p[^>]*>/i', '', $string);

但是,这会删除所有 <p></p> 标签。如何将其调整为仅去除第一个 <p> 和最后一个 </p> 标签,即使在我的字符串的其他位置有其他此类标签?

非常感谢!

使用一个额外的参数作为 1。 看到这个 post。 Using str_replace so that it only acts on the first match?

最后一个 p 标签使用从后面搜索。或者你可以反转字符串搜索并从头开始替换。不要忘记相应地更改正则表达式。

你的第一个正则表达式可能是这样的

$str=preg_replace('/<p>/', '', $str,1);

现在反转字符串并执行相同的操作,但更改正则表达式。

$str=strrev ($str);

$str=preg_replace('/>p\/</', '', $str,1);

现在再次反转字符串

$str=strrev ($str);

考虑到理解代码会很耗时,我会根据这些讨论使用 str_replace:

Using str_replace so that it only acts on the first match?

PHP Replace last occurrence of a String in a String?

所以像这样:

// Remove first occurrence of '<p>'
$pos = strpos( $string, '<p> );
if( $pos !== false ){
    $string = substr_replace( $string, '<p>', $pos, 3 );
}
// Remove last occurrence of '<p>'
$pos = strrpos( $string, '</p>' );
if( $pos !== false ){
    $string = substr_replace( $string, '</p>', $pos, 3 );
}