1

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!

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
Richard Tinkler
  • 1,635
  • 3
  • 21
  • 41
  • 1
    Don't use a regex to process HTML: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Bart Friederichs Nov 16 '15 at 10:34
  • http://stackoverflow.com/questions/3835636/php-replace-last-occurence-of-a-string-in-a-string is applicable if you edit it – online Thomas Nov 16 '15 at 10:35
  • 1
    @BartFriederichs: Well, technically it is a string (TS said so). Given enough constraints, regexp and html go together just fine. Besides, Chuck Norris can parse html with regexp. ;) – Herbert Van-Vliet Nov 16 '15 at 11:06
  • 1
    @HerbertVan-Vliet Yes, I just want to warn him for the "let's-use-a-regex-to-parse-HTML" route of solving problems. And of course Chuck Norris can. – Bart Friederichs Nov 16 '15 at 11:41

2 Answers2

1

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);
Community
  • 1
  • 1
Partha Sarathi Ghosh
  • 10,936
  • 20
  • 59
  • 84
0

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 );
}
Community
  • 1
  • 1