0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is just what I was after, thank you! Also realized that in my case I needed an else statement to just return the $sportstr if it doesn't match the key, after that it worked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.