简体   繁体   中英

Help using PHP Regular Expression

I have a string and I want to extract a part, but I'm not familiar with Regex. This is the string :

<p>You have all kinds of great energy coming down today, and should be able to get almost anything started. It's one of those days when you need to be busy pretty much every waking minute!
</p> 
        <p>More horoscopes! Check your: <a href="http://horoscopes.astrology.com/index/dailysinglesindex.html?dst=rss%7Cast_horo%7Cdo">Daily Single's Love</a>, <a href="http://horoscopes.astrology.com/index/dailyromindex.html?dst=rss%7Cast_horo%7Cdo">Daily Couple's Love</a>, <a href="http://horoscopes.astrology.com/index/dailytechindex.html?dst=rss%7Cast_horo%7Cdo">Daily Work</a>, <a href="http://horoscopes.astrology.com/index/weeklyromindex.html?dst=rss%7Cast_horo%7Cdo">Weekly Romantic</a>, <a href="http://horoscopes.astrology.com/index/monthlyfitindex.html?dst=rss%7Cast_horo%7Cdo">Monthly Fitness</a>, <a href="http://horoscopes.astrology.com/?dst=rss%7Cast_horo%7Cdo">more</a> ...</p> 
        <p>Today's Free Sample Reading: Transform your love life or relationship in the coming year with our <a href="http://shop.astrology.com/scripts/runisa.dll?AO:TPROD::RSSHORODO,offer=null&dst=rss%7Cast_horo%7Cdo_offer&prodID=7014">free sample Love in the New Year tarot reading</a> at Astrology.com.</p> 
        <p><a href="http://www.ivillage.com/redir?iv_url=http://www.keen.com/documents/special_offers/astrology-lp1.asp?TID=FMkPKWEY">Is it really over? Find out if he'll come back with a Free Psychic Love Reading. </a></p><img src="http://feeds.feedburner.com/~r/dailyoverview/~4/-RSJe5GW1h0" height="1" width="1"/>

I want to extract the first paragraph only :

<p>You have all kinds of great energy coming down today, and should be able to get almost anything started. It's one of those days when you need to be busy pretty much every waking minute!
</p>

Thanks in Advance,

Well you can do that with RegExp but it is not advisable. Refer Parsing Html The Cthulhu Way

I can foresee you might be fetching some HTML (or reading from a file) and want to extract some text our of it. HTML is for layout, not a structured language for data storage.

preg_match_all('/<p>.+?<\/p>/',$yourString, $result);

$p1 = $result[0][0];

print $p1;

This will only work if your P tags are <p>content.</p> As soon as you start adding attributes it will break. Which is one of the reasons why you shouldn't use regex to extract HTML in the first place.

You want to use a DOM parser, not a regular expression. Here's one , and here's another .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM