2

我正在寻找一种从该字符串中获取以下数据的方法

DON'T FLOP - ‬Rap Battle - Illmaculate Vs Tony D

DON'T FLOP - ‬Rap Battle - $var1 Vs $var2

所以我可以结束 $var3 = $var1 Vs $var2

问题是对手的名字可以包含多个单词,而我可以一直到vs右边的对手的句子末尾,我无法界定对手名字的开头,我呢?

如何从 - 之后的空白处进行检查,在 vs 处停止并重新开始 $var2 直到句子结束?

4

2 回答 2

1

(.+?)左侧的非贪婪捕获组Vs,在-and 空格之后应该获取名字。只要您始终有空间,-这应该可以正常工作。\s+如有必要,允许多个空格。

$pattern = '/Rap Battle -\s+(.+?)\s+Vs\s+(.+)$/';

$string = "DON'T FLOP - Rap Battle - Illmaculate Vs Tony D";
preg_match($pattern, $string, $matches);
var_dump($matches);

array(3) {
  [0]=>
  string(34) "Rap Battle - Illmaculate Vs Tony D"
  [1]=>
  string(11) "Illmaculate"
  [2]=>
  string(6) "Tony D"
}

$var1 = $matches[1];
$var2 = $matches[2];
于 2012-07-03T01:50:22.613 回答
0
$text = "DON'T FLOP - Rap Battle - Illmaculate Vs Tony D";
$regex = '%Rap Battle - (.*?) Vs (.*)$%';
preg_match($regex, $text, $array);

$array[0] = entire string match.
$array[1] = first opponent.
$array[2] = 2nd opponent.
于 2012-07-03T01:55:56.067 回答