0

I have a custom field called description that stores a text like this:

<h2>This is a heading</h2>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo

I need to delete the heading inside (<h2.*?<\/h2>) only.

How can I do this?

bpy
  • 1,150
  • 10
  • 27

2 Answers2

0
$removed = preg_replace( "/<h2.*?<\/h2>/", "<h2><\/h2>", $original );

This will remove the text in the tag. Replace with an empty string to remove it altogether.

patrick
  • 11,519
  • 8
  • 71
  • 80
  • Regex should not be used on valud html. This question is a mega-duplicate which should br closed instead of answered. – mickmackusa Nov 21 '19 at 20:09
0

Use substr to cut it into two parts. One till <h2> and the other part beginning from </h2>. You can get the index of the beginning of these tags with strpos.

$string = '<h2>This is a heading</h2> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo';

$new_string1 = substr($string, 0, (strpos($string, '<h2>')+4)); 
$new_string2 = substr($string, strpos($string, '</h2>'));  

//Will output: <h2></h2> Lorem ipsum ...
echo $new_string1 . $new_string2;
davidev
  • 7,694
  • 5
  • 21
  • 56