Page 1 of 1

Fastest way to parse a string

Posted: Thu Nov 25, 2010 5:06 pm
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

Re: Fastest way to parse a string

Posted: Thu Nov 25, 2010 5:48 pm
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);

Re: Fastest way to parse a string

Posted: Sat Nov 27, 2010 2:29 pm
by onecurlyfry
Thanks that's totally rad. Appreciate the help.