Using regex in a string for strpos()

brinard sweeting picture brinard sweeting · Dec 22, 2011 · Viewed 34.8k times · Source

I want to get the scripts to search the $open_email_msg which different e-mails will have different info but the same format as below.

I haven't really used regex much, but what i want to do is whenever i have it to search the string it would search for "Title: [data for title]", "Categories: [data for categories]. I am asking because i don't think something like

strpos($open_email_msg, "Title: (*^)"); 

would even work.

This is just a snippet of the whole code, the rest inserts the info into a MySQL table and then is posted to a News Article on the site.

Can somebody help me find a solution to this please?

Strict e-mail message format:

News Update
Title: Article Title
Tags: tag1 tag2
Categories: Article Category, 2nd Article Category
Snippet: Article snippet.
Message: Article Message. Images. More text, more text. Lorem impsum dolor sit amet.

<?php
    //These functions searches the open e-mail for the the prefix defining strings.
        //Need a function to search after the space after the strings because the subject, categories, snippet, tags and message are constant-changing.
    $subject = strpos($open_email_msg, "Title:");       //Searches the open e-mail for the string "Title" 
        $subject = str_replace("Title: ", "" ,$subject);
    $categories = strpos($open_email_msg, "Categories:");       //Searches the open e-mail for the string "Categories"
    $snippet = strpos($open_email_msg,"Snippet");           //Searches the open e-mail for the string "Snippet"
    $content = strpos($open_email_msg, "Message");  //Searches the open-email for the string "Message"
    $tags = str_replace(' ',',',$subject); //DDIE
    $uri =  str_replace(' ','-',$subject); //DDIE
    $when = strtotime("now");   //date article was posted
?>

Answer

cambraca picture cambraca · Dec 22, 2011

Try using the PREG_OFFSET_CAPTURE flag for preg_match. Something like this:

preg_match('/Title: .*/', $open_email_msg, $matches, PREG_OFFSET_CAPTURE);
echo $matches[0][1];

This should give you the initial position of the string.

Note that the regex I'm using could be wrong and not take into account line endings and stuff, but that's another subject. :)

EDIT. A better solution for what you want (if I understand it correctly) would be something like this:

$title = preg_match('/Title: (.*)/', $open_email_msg, $matches) ? $matches[1] : '';

You'd then get the title into the $title variable, and an empty string if no title was found.