Home > Net >  Replace with value from array and remove everything else
Replace with value from array and remove everything else

Time:12-24

I have an array which associates Sports leagues with their specific Sport. I want to find the league and return the sport. I've tried using strtr but that doesn't seem to be the correct way.

$leagues = array("NHL" => "Ice hockey", "Premier League" => "Football"); 
$sport = strtr("NHL",$leagues);

This works and returns "Ice hockey". The problem is that the original data might contain different variations of the Sport leagues, so there might be both "NHL" and "NHL Playoffs" that I would like to both return only as "Ice hockey" without having to specify all variations in the array.

$leagues = array("NHL" => "Ice hockey", "Premier League" => "Football"); 
$sport = strtr("NHL Playoffs",$leagues);

So this for example, returns "Ice hockey Playoffs" when I would like to return only "Ice hockey". How can I solve this?

CodePudding user response:

strtr is to replace a string by array key/value pairs. In order to achieve your goal, you may use a loop and regular expression.

$leagues = ["NHL" => "Ice hockey", "Premier League" => "Football"]; 
$sportstr = "NHL Playoffs";
$sport = "";
foreach($leagues AS $key=>$val){
    if(preg_match("/".$key."/", $sportstr)){
        $sport = $val;
        break;
    }
}
echo $sport;
//this will return Ice hockey
  •  Tags:  
  • php
  • Related