PHP 抓住某个词并忽略字符串中的其余部分

PHP Grab a certain word and ignore the rest in a string

我试图在大约 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).
$username = explode(' ',$lines)[1];

这可能超出您的预期,但这里有一种避免正则表达式的方法。

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

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

<?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];
}
?>

会打印出"Hagiwara".

执行此操作的正则表达式并不复杂。更防弹恕我直言

$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/>';

}