Reputation: 1643
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
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
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