0
<p>Blockbuster event so big that the excerpt will not even fit into the allotted space.</p> 
<p> The post 
     <a rel="nofollow" href="http://example.com/event/sample-event/">Sample Event</a> 
    appeared first on 
     <a rel="nofollow" href="http://example.com">abc</a>.
</p>

$desc = preg_replace('/<p>(.*)<\/p>/i', '$1', $event->description);
$desc = substr($desc, 0, strpos($desc, 'The post'));

Hey, I'm trying to strip tags and extract only the part until 'The post'. I have tried /<p>(.*)<\/p>/ but this returns both parts of the description. To achieve the end result I had to take a sub string. Is there a regex that takes care of this so I don't need to use substr()?

Sarath Chandra
  • 1,850
  • 19
  • 40
Adam
  • 9
  • 2
  • [Don't parse HTML with regex!](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – klenium Aug 14 '15 at 22:29

1 Answers1

1

Make the expression "ungreedy":

$desc = preg_replace('/<p>(.*)<\/p>/Ui', '$1', $event->description);

or

$desc = preg_replace('/<p>(.*?)<\/p>/i', '$1', $event->description);

If you want to keep just the contents of the first <p> tag, it may be simpler to preg_match and keep the result:

preg_match('/<p>(.*)<\/p>/Ui', $event->description, $results);
$desc = $results[1];

Here's a demo: https://ideone.com/KFLdnI

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115