O'Reilly

Get the Intro: PHP Paragraph Regular Expression

By on  

Recently I was playing around with WordPress' wp_posts table. I wanted to grab the basic information about my posts (ID, title, content, slug) and build a quick summary list of them. One problem I ran into was creating a content "intro." Luckily a quick regular expression allowed me to create the intro.

The PHP

preg_match("/<p>(.*)<\/p>/",$post['post_content'],$matches);
$intro = strip_tags($matches[1]); //removes anchors and other tags from the intro

The above code extracts the first paragraph in a string. Since all of my posts begin with an introductory paragraph, this type of system will work.

Track.js Error Reporting

Recent Features

  • Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

  • CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • Prevent Page Zooming in Mobile Browsers

    Ever since I got my iPhone, I've been more agreeable in going places that my fiancee wants to go. It's not because I have any interest in checking out women's shoes, looking at flowers, or that type of stuff -- it's because my iPhone lets...

  • iPhone Click Effect Using MooTools or jQuery

    One thing I love about love about Safari on the iPhone is that Safari provides a darkened background effect when you click a link. It's the most subtle of details but just enforces than an action is taking place. So why not implement that...

Discussion

  1. A few things I’d recommend. allow for a CSS style in your regex, make the regex case-insensitive, and have the regex treat the subject as a single line.

    preg_match("/<p.*>(.*)<\/p>/is",$post['post_content'],$matches);
    
  2. Good suggestion Matt!

  3. @Matt, you probably meant:

    preg_match(”/<p[^>]*>(.*)<\/p>/is”,$post['post_content'],$matches);
    

    Otherwise, it would match everything between the first <p> tag and the last </p>

  4. @Jeremy, that’s it! i knew i was forgetting something.

  5. Grouchy Smurf

    Has one of you ever read the doc ?

    preg_match('#<p[^>]*>(.*)</p>#isU', $post['post_content'], $matches);
    

    The “i” modifier allow paragraph tag name to be lower case or upper case. The “s” modifier allow dot metacharacter to match all characters, including newlines. The “U” modifier make pattern really matching only the first paragraph instead of everything between the first p end the last p. Using the “#” delimiter for your pattern make it more readable when dealing with HTML tags and using single quote to declare the pattern string don’t start PHP automatic search for somes vars to replace.

  6. David, are you doing this from within wordpress via a plugin or something, or outside wordpress and just accessing the database?

    If the first one there are better ways of doing it by using the WP functions, like the_excerpt_rss()…

  7. Cautious User

    Slight correction to Grouchy Smurf’s regex:

    $pattern = “#]*>(.*?)#is”;

  8. What does this code actually do? Is there any way to style the first paragraph by separating it first in PHP, then using CSS?

  9. nice idea, but how do I add the code? how if i just paste it after the_title ? is it works if i do that?

  10. Rich

    This worked like a champ, but lets say I wanted to get the rest of the content now, minus the intro paragraph? how would I go about doing that? for example. i want to show the intro paragraph using your code, then create a div that would enclose the rest of the actual content that I would be able to toggle through a read more link.

  11. Hi,
    I’m in a trouble with php paragraph replace. I’ve following para

    {tab=Sed facilisis consequat libero}Fusce eu ligula purus, eu ultricies nisl.

    Fusce eu ligula purus, eu ultricies nisl. Curabitur sed leo felis. {/tab}

    {tab=Curabitur ultricies sapien}Sed facilisis consequat libero, at tincidunt neque tristique vitae. {/tab}

    my aim is to replace {tab=name}something{/tab} to something

    Reg exp. i’m using is: /({tab.+?})(.*\S)({\/tab})/s

    Its working fine with single line or para. but not with multiline.

    Can anybody suggest how to fix it.
    Thanks in Advance…

  12. Bips

    Could you please help me to preg match two or more paragraph,I mean all the paragraph from the $post[‘post_content’]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Loading Static Templates for Intern Testing

    I use Intern by SitePen for all of my JavaScript functional testing.  Intern has loads of features other functional test frameworks don't and it's completely Promise-based -- something I got very used to when I used the Dojo Toolkit every day. Async test creation can...

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...