使用PHP剥离1st<;p>;并且最后</p>;仅在字符串中


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

我已经为这个问题找到了许多preg_replace解决方案,最接近的是:

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

然而,这会剥离所有<p>&</p>标签。如何将其调整为仅剥离第一个<p>和最后一个</p>标记,即使在我的字符串中还有其他这样的标记?

非常感谢!

使用一个额外的参数作为1。请参阅此帖子。使用str_replace使其只作用于第一个匹配?

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

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

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

现在反转字符串并执行相同的操作,但更改regex。

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

现在再次反转字符串

$str=strrev ($str);

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

使用str_replace使其只作用于第一个匹配?

PHP替换字符串中最后一个字符串?

所以类似于:

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