0
<p class="myClass">你好</p><p class="myClass">你好</p></div> <div class="myDiv">Integer in ante sit amet tellus sodales sagittis non sit amet nisi. Integer sollicitudin, orci nec tincidunt laoreet, dui quam tempor risus, sed mollis nisl libero nec ligula</div><p class="myClass">你好</p>

I am trying to replace only <p class="myClass">你好</p> But whole string is being replaced.

Pattern:

$pattern = "/<p class=\"myClass\">(.)*<\/p>/";
preg_replace($pattern,"",$string);

When I Put p tag on new line it works good. But having p tag Without space replacing all the string.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
phpnerd
  • 850
  • 1
  • 10
  • 25

2 Answers2

0

The (.*?) select all character but you need to select <p> so use [^<]+ instead that select every character except <.

$pattern = "/<p class=\"myClass\">[^<]+<\/p>/";
preg_replace($pattern, "", $string);

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • 1
    This won't work if any other HTML element (e.g. ``) is in the paragraph (now, only OP knows if that may or may not happen). PS: I wasn't the one downvoting the answer tho :) – Jeto Sep 27 '18 at 06:51
  • @Jeto It doesn't mention in question – Mohammad Sep 27 '18 at 06:59
0

Try this :-

$str = '<p class="myClass">你好</p><p class="myClass">你好</p></div> <div class="myDiv">Integer in ante sit amet tellus sodales sagittis non sit amet nisi. Integer sollicitudin, orci nec tincidunt laoreet, dui quam tempor risus, sed mollis nisl libero nec ligula</div><p class="myClass">你好</p>';
preg_replace('#<p(.*?)>(.*?)</p>#is', '', $str);

It will replace all the <p> tags from the string.
Check this Fiddle :- https://3v4l.org/Un9Jh

Yash Parekh
  • 1,513
  • 2
  • 20
  • 31