Mac Taylor
Mac Taylor

Reputation: 5166

extracting different parts of a string in php

I have a website that all its stories' title are like this :

new job alert from chicago {latest reservation : 3/5/2011}
new job alert from NY {latest reservation : 3/4/2011}
new job alert from LA {latest reservation : 3/3/2011}

now in php i need to extract latest reservation part

$atest_reservation = ?

$story_title_without_reservation_date = ?

i tried functions like strstr() or preg_replace() but couldn't succeed to reach my goal

thanks

Upvotes: 1

Views: 139

Answers (5)

salathe
salathe

Reputation: 51970

Another option is to use sscanf().

sscanf(
    $title,
    '%[^{]{latest reservation : %[0-9/]}',
    $story_title_without_reservation_date,
    $latest_reservation
);

Upvotes: 0

user142162
user142162

Reputation:

$str = 'new job alert from LA {latest reservation : 3/3/2011}';

preg_match('/^(.*) \{latest reservation : ([^\}]*)\}$/', $str, $matches);

list(,$story_title_without_reservation_date, $latest_reservation) = $matches;

// $story_title_without_reservation_date = "new job alert from LA"
// $latest_reservation = "3/3/2011"

Upvotes: 3

Jakub
Jakub

Reputation: 20473

Easy, do this:

$entry = "new job alert from chicago {latest reservation : 3/5/2011}"

$string = explode("{", $entry);
echo $string[0]; // new job alert from chicago 
echo $string[1]; // latest reservation : 3/5/2011}

Then clean it up however you want.

Upvotes: 1

Mr. Llama
Mr. Llama

Reputation: 20919

I'm not exactly sure which parts you're trying to extract in specific, but the following should work:

preg_match_all("/new (.*) from (.*) {latest reservation : (.*)}/", $data, $matches)

That will match the (if I'm reading that correctly) the job alert name, the city, and the date from the alerts. It'll match all of them, but if you're doing this line by line, you can use a standard preg_match instead of preg_match_all.

Upvotes: 0

dLobatog
dLobatog

Reputation: 1741

Try

substr ( string $string , int $start [, int $length ] )

In order to get the first 16 characters it would be

substr ($string , 0, 15 )

So try to save all the strings you have in variables or in an array and get whichever part you want with this.

If you have any doubt, comment below please :)

Upvotes: 1

Related Questions