2015-08-14 32 views
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')); 

嘿,我试图剥离标签,只提取部分,直到'帖子'。我尝试过/<p>(.*)<\/p>/,但这会返回说明的两个部分。为了达到最终结果,我不得不采取一个子字符串。有没有一个正则表达式来处理这个问题,所以我不需要使用substr()?正则表达式 - 我的代码不行为

+0

[不要用正则表达式解析HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – klenium

回答

1

使表达式“ungreedy”:

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

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

如果你想保持第一<p>标签的内容之外,它可能是简单preg_match并保持结果:

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

下面是演示:https://ideone.com/KFLdnI