Richard Tinkler
Richard Tinkler

Reputation: 1643

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

I have found a number of preg_replace solutions for this problem, the closest one being this:

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

However, this strips ALL <p> & </p> tags. How do I adjust this to ONLY strip the FIRST <p> and LAST </p> tags, even if there other such tags positioned elsewhere in my string?

Many thanks!

Upvotes: 1

Views: 1111

Answers (2)

Herbert Van-Vliet
Herbert Van-Vliet

Reputation: 764

Considering it will be time consuming to understand the code, I would just use str_replace as per these discussions:

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

PHP Replace last occurrence of a String in a String?

So something like:

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

Upvotes: 0

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Use an extra parameter as 1. See this post. Using str_replace so that it only acts on the first match?

For last p tag use search from behind. Or u can reverse the string search and replace from start then. Dont forget to change the regex accordingly.

Ur first regex could be like this

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

Now reverse the string and do the same but change regex.

$str=strrev ($str);

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

Now reverse the string again

$str=strrev ($str);

Upvotes: 1

Related Questions