Search code examples
phplistreplace

How to replace strings into a foreach before explode command usign PHP


I have a foreach where I extract football matches; the format of the football match string is like

Manchester City - Manchester United

and I use "-" to explode them, but I have a problem with some football team name because they have that character into the name, like

V-Varen Nagasaki

so I thought to replace the name without that character, like

"V-Varen Nagasaki","V Varen Nagasaki"

This is the webpage link: link This is my part of code where I explode them:

`$c=0; $b=0; $o=0; $z=0; $h=0; $j=0; 
foreach ($titles as $match) {
    
   
    list($home, $away) = explode('-', $titles[$z++]->innertext); // <- explode


$home = strip_tags($home);
$away = strip_tags($away);
$uniquefield = $home . ' ' . $away;`
}

So, you can see I explode titles (football matches) in two variables list home and away, but I am not sure where I have to put all my replaces teams list.

Every name is different so I can't do a general replace, but specific for each team

Thanks for your helping


Solution

  • If you have football match strings where team names might contain hyphens and you want to split them correctly, you can use a regular expression to dynamically handle the splitting. Here's how you can achieve this in PHP:

    <?php
    $titles = [
        "Manchester City - Manchester United",
        "V-Varen Nagasaki - Tokyo Verdy",
        "Real Madrid - Barcelona",
    ];
    
    foreach ($titles as $match) {
    
        preg_match('/^(.*) - (.*)$/', $match, $result);
        if ($result) {
            $team1 = $result[1];
            $team2 = $result[2];
       
            echo "Team 1: $team1, Team 2: $team2\n";
        } else {
            echo "Invalid match format: $match\n";
        }
    }
    

    This approach ensures that team names with hyphens are correctly handled, making it robust for various team name formats.