简体   繁体   中英

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

My PHP strings look like this:

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

I need to extract the NUMBER, the names from the strings :

[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)

Demo here

In your PHP file :

$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:

$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. group 1 will have the time, group 2 will have the home team name and group 3 will have the away team name.

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

Here you can see the regex demo .

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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