Fastest way to parse a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
onecurlyfry
Forum Newbie
Posts: 5
Joined: Tue Jul 29, 2008 3:01 pm

Fastest way to parse a string

Post by onecurlyfry »

I am working with an API that returns an XML file. I have a line of code that returns the title.
$keyword = $xmlObj->entry->source->title;

An example of the returned title is:
Twitter - Keyword - Notices - Nike

What I really want $keyword to be is "Nike" - so, given that string above, whats the fastest way to pull that out? I know I could do a substr, or even use explode, such as:
$kw = explode(" - ", $keyword);
$keyword = $kw[3];

I'm going to be iterating through up to 10,000 records, writing to a db, so I'd like to know the blazing fastest way to do this.

Thx,

Scott
mikecampbell
Forum Commoner
Posts: 38
Joined: Tue Oct 12, 2010 7:26 pm

Re: Fastest way to parse a string

Post by mikecampbell »

This is about 50% faster in my test (1000000 iterations)

Code: Select all

$p = strrpos($keyword, ' - ');
if ($p!==false) $keyword = substr($keyword, $p+3);
onecurlyfry
Forum Newbie
Posts: 5
Joined: Tue Jul 29, 2008 3:01 pm

Re: Fastest way to parse a string

Post by onecurlyfry »

Thanks that's totally rad. Appreciate the help.
Post Reply