如何提取由空格分隔的PHP字符串的某些部分

时间:2014-11-21 11:44:15

标签: php regex string str-replace explode

我的PHP字符串如下所示:

$test1= '   1    AAA vs SSS    ';
$test2= '  2        GGG vs FFF ';

我需要提取NUMBER,字符串中的名称:

[0] => stdClass Object
    (
        [no] => 1
        [one] => AAA 
        [two] => SSS    
    )

我该怎么做?

4 个答案:

答案 0 :(得分:1)

^(\s| )*([0-9:]+)\s+(\S.*\S)\svs\s(\S.*\S)\s*$

在替换中,时间将为1美元 主队2美元 3美元的客场球队 (第三场比赛的得分为0-3)

Demo here

在您的PHP文件中:

$game1 = ' 04:60    FC Heidenheim 1846 vs SV Sandhausen    ';
//I strip the  's first to have a simpler regexp
$game1 = str_replace(' ',' ',$game1);
preg_match ("@^\s*([0-9:]+)\s+(\S.*\S)\svs\s(\S.*\S)\s*$@", $game1, $matches); 
$result =new stdClass;
$result->time = $matches[1];
$result->hometeam = $matches[2];
$result->awayteam = $matches[3];

var_dump( $result );

答案 1 :(得分:0)

你应该在你的字符串上使用trim(), 之后,如果结构字符串没有改变:

$game = trim($game);

$hour = substr($game,0,5);

$opponents = substr($game, 6);

$opponents = explode("vs",$opponents);

所以数组看起来

array(
'hour'=>$hour,
'home_team'=>$opponents[0],
'away_team'=>$opponents[1] );

我没有测试它,但它看起来像这样

答案 2 :(得分:0)

我不懂PHP,但您可以使用以下正则表达式来获取值。 group 1将有时间,group 2将拥有主队名称,group 3将拥有客队名称。

^([\d:]+)\s+([\w\s\d]+)\s+vs\s+([\w\s\d]+)\s?$

Here you can see the regex demo

答案 3 :(得分:0)

你可以尝试类似的东西,

$test1= ' 1    AAA vs SSS    ';
$test2= '  2        GGG vs FFF ';

$test1 = dataFormatter($test1);
$test2 = dataFormatter($test2);

print_r($test1);
print_r($test2);

function dataFormatter($data)
{
    $data= explode(" ",$data);
    foreach($data as $value)
    {
        if($value && $value!= vs)
            $newData[] = $value;
    }
    return $newData;
}

输出:

Array
(
[0] => 1
[1] => AAA
[2] => SSS
)

Array
(
[0] => 2
[1] => GGG
[2] => FFF
)