0

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</uri>
</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!

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Alexia
  • 1
  • 1

2 Answers2

3

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
  • 5,386
  • 1
  • 22
  • 18
1

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
  • 395,085
  • 80
  • 655
  • 663