简体   繁体   English

如何通过PHP从Search API中提取Twitter用户名

[英]How to extract Twitter username from Search API via PHP

The Twitter Search api returns results in ATOM/XML format which look like this: Twitter Search api以ATOM / XML格式返回结果,如下所示:

<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: 在我的PHP中,我可以将名称字段作为变量获取,因此它看起来像这样:

$names = "username (Friendly Name)"

But I want to use PHP to extract them as seperate variables, like this: 但是我想使用PHP将它们提取为单独的变量,如下所示:

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

TIA! TIA!

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. 假定括号在这两个名称中均无效。

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) (请注意,“ string ”,“ length ”以及所有这些仅是var_dump的输出,而不是实际变量的内容)


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] 这意味着它们将位于$m[1]$m[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM