Nick
Nick

Reputation: 9373

Get text following a keyword and stopping at new line in PHP

I have a document that a string that has a dynamic date but also contains other data I don't need. A typical string looks something like this

\n\n  \n     \n  Date: Jan. 25, 2012\n  \n  Location:\n     \n       \n         Ukraine,\n       \n      

I wanted to grab the information between Date: and \n as the date shows up in the form above Month. Day, Year - but also as numeric values such as 1.25.2012

Is there a way to do this?

Upvotes: 0

Views: 200

Answers (3)

Bert
Bert

Reputation: 1029

Try use explode and specify the delimiters. and store it in an array.

Upvotes: 0

TecBrat
TecBrat

Reputation: 3729

There might be a more elegant way, but I have done something like that before:

<?php
$string="\n\n  \n     \n  Date:\n\n  \n     \n  Date: Jan. 25, 2012\n  \n  Location:\n     \n       \n         Ukraine,\n       \n \n  \n  Location:\n     \n       \n         Ukraine,\n       \n ";


list($trash,$keep)=explode('Data:',$string); 
//or 'Date: ' if you do not want that leading space.
list($keep,$trash)=explode("\n",$keep);

echo $keep;
// Jan. 25, 2012
?>

Upvotes: 0

deceze
deceze

Reputation: 522085

if (preg_match('/Date: ([^\n]+)/', $line, $match)) {
    echo $match[1];
}

$match[1] will contain the date, which is any match after Date: that is not a newline. How to parse it from there, you'll have to decide.

Upvotes: 2

Related Questions