views:

297

answers:

3

The Twitter Search api returns results in ATOM/XML format which look like this:

<author>
  <name>username (Friendly Name)</name>
  <uri>http://twitter.com/username&lt;/uri&gt;
</author>

In my PHP I can get the name field as a variable, so it would look like this:

$names = "username (Friendly Name)"

But I want to use PHP to extract them as seperate variables, like this:

$username = "username"
$friendlyName = "Friendly Name" (without parantheses)

TIA!

+1  A: 

Something like this should do, I suppose :

$names = "username (Friendly Name)";
if (preg_match('/^(.*?) \((.*)\)$/', $names, $m)) {
    var_dump($m[1], $m[2]);
}

And you're getting, in this case :

string 'username' (length=8)
string 'Friendly Name' (length=13)

(Note the "string", "length", and all that are only the output of var_dump, and not the actual variables content)


Basically, the regex is matching :

  • Anything from the beginning of the string to a space
  • Then, anything between ()
  • And those are the two returned patterns -- as they are between non-escaped () ; which means they'll be in $m[1] and $m[2]
Pascal MARTIN
+3  A: 

A non-regex solution:

$names = 'username (Friendly Name)';
list($username, $friendlyName) = explode('(', $names);
$username = trim($username);
$friendlyName = trim($friendlyName, ')');

Assumes that parentheses are not valid in either name.

GZipp
A: 

Hey guys,

Ive written a script that will query the Twitter search API for a given query entered by means of a form and then having been looking for ways to chomp this xml into a list of usernames, found this page.

Gzipp's answer seems like a good option for me. I dont think there are any usernames that contain parentheses but the main reason is that I understand it .. apart from .. how to hook it into my script. My ultimate goal is to crunch the list of usernames returned into a plain text file for onward processing by a further script that will follow the returned users for a given account.

Im new to the site and have read as many faq as I could find so i hope im not breaking any rules or protocols in making this request on an old thread.. I guess what Im looking for are some of the meat and potatoes that would go around the snippit:-

=============================================

$names = 'username (Friendly Name)';

list($username, $friendlyName) = explode('(', $names);

$username = trim($username);

$friendlyName = trim($friendlyName, ')');

================================================

in order to be able to parse the usernames off into a file...

Im new to PHP, learning as I go, but sometimes I hit a brick wall...

TIA,

Wheen

PS I guess what I am asking is "how does pascal get the $names variable to contain whats in the atom?