PHP获取某个单词并忽略字符串中的其余部分

时间:2015-02-27 23:29:12

标签: php regex strpos

我试图只抓取大约30行长的句子列表中的用户名。之后我能够获取用户名和所有内容,但我不想在用户名之后获取所有内容。

的test.txt

[India] Hagiwara has been inactive for 33 days (last seen: Sun Jan 25 23:35:35 2015).
[India] Psyborg has been inactive for 35 days (last seen: Fri Jan 23 18:43:58 2015).
[Echo] Pela has been inactive for 31 days (last seen: Tue Jan 27 20:00:30 2015).

PHP

$data = file('test.txt');

foreach ($data as $lines) {

if (($pos = strpos($lines, "]")) !== FALSE) { 
    $string = substr($lines, $pos+1); 
}

echo $string . '<br />';
}

输出

Hagiwara has been inactive for 33 days (last seen: Sun Jan 25 23:35:35 2015).

4 个答案:

答案 0 :(得分:2)

$username = explode(' ',$lines)[1];

答案 1 :(得分:2)

这可能比您预期的要多,但这是一种避免正则表达式的方法。

$string = substr($lines, $pos+2);
$string = substr($string, 0, strpos($string, ' '));

答案 2 :(得分:1)

给出您的示例字符串并基于用户名永远不会包含空格字符的假设:

<?php
$input_line = "[India] Hagiwara has been inactive for 33 days (last seen: Sun Jan 25 23:35:35 2015).";
if (preg_match("/\[.+\]\s*(\S+)\s*.*/", $input_line, $output_array) == 1) {
    echo $output_array[1];
}
?>

将打印出来&#34; Hagiwara&#34;。

答案 3 :(得分:0)

要做到这一点的正则表达式并不是那么复杂。它更具弹性imho

$str1 = '[India] Hagiwara has been inactive for 33 days (last seen: Sun Jan 25 23:35:35 2015).';

$str2 = '[India] Psyborg has been inactive for 35 days (last seen: Fri Jan 23 18:43:58 2015).';

$str3 = '[Echo] Pela has been inactive for 31 days (last seen: Tue Jan 27 20:00:30 2015).';

$strs = array($str1,$str2,$str3);

foreach ($strs as $key => $val) {

  //strips the initial bracketed string from the beginning of the line
  $trimmed_val = preg_replace("/^\[\w+\]\s/",'',$val);

  //grabs the first word from the trimmed string (user in this case)
  preg_match("/^\w+\s/",$trimmed_val,$users);

  //prints out a list of users for demonstration
  echo $users[0] . '<br/>';

}