简体   繁体   English

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

[英]How can I extract some parts of a PHP string that are separated by spaces

My PHP strings look like this: 我的PHP字符串如下所示:

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

I need to extract the NUMBER, the names from the strings : 我需要从字符串中提取NUMBER和名称:

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

How can I do this? 我怎样才能做到这一点?

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

in the replace, time will be in $1 home team in $2 away team in $3 (and the score for the third match will be 0-3) 在替换中,时间将在$ 1的主队中在$ 2的客队中在$ 3中(第三场比赛的比分将为0-3)

Demo here 在这里演示

In your PHP file : 在您的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 );

you should use trim() on your string, after it if the structure string does not change: 如果结构字符串不变,则应在字符串之后使用trim():

$game = trim($game);

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

$opponents = substr($game, 6);

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

so the array look 所以数组看起来

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

i didnt test it but it s look like this 我没有测试,但看起来像这样

I don't know PHP, but you can use the below regex to get the values. 我不知道PHP,但是您可以使用下面的正则表达式获取值。 group 1 will have the time, group 2 will have the home team name and group 3 will have the away team name. 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 . 在这里,您可以看到regex演示

You can try something like, 您可以尝试类似的方法,

$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;
}

Output: 输出:

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

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

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

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