v3ntus
v3ntus

Reputation: 239

Replace defined string if condition X applies

I have the following php line:

define("CITY_NAME", $city->originalCityname);

which displays the name of a city (for example: "Rome").

If originalCityname is or ends with "Rome", I'd like to add " (Italy)" so it will display "Rome (Italy)" and not just "Rome".

How can I achieve this in php?

EDIT

Thank you all guys! What about if "Rome" is part of the string? For example "Name of a Town - Rome" changed to "Name of a Town - Rome (Italy)"? Can I add " (Italy)" if the value ENDS with "Rome"? Thanks again!

Upvotes: 2

Views: 38

Answers (2)

hellcode
hellcode

Reputation: 2698

You cannot change a constant after you have defined it. So you have to set the value once:

if($city->originalCityname == "Rome") {
    define("CITY_NAME", $city->originalCityname)." (Italy)";
} else {
    define("CITY_NAME", $city->originalCityname);
}

EDIT: If you need to check if the value ends with "Rome" just use:

if(substr($city->originalCityname, -4) == "Rome") {
    define("CITY_NAME", $city->originalCityname)." (Italy)";
} else {
    define("CITY_NAME", $city->originalCityname);
}

EDIT: If you need to check if the value ends with "Rome" or "Milan" (to add Italy) or "London" (to add United Kingdom) just use:

if(substr($city->originalCityname, -4) == "Rome" or substr($city->originalCityname, -5) == "Milan") {
    define("CITY_NAME", $city->originalCityname)." (Italy)";
} elseif(substr($city->originalCityname, -6) == "London") {
    define("CITY_NAME", $city->originalCityname)." (United Kingdom)";
} else {
    define("CITY_NAME", $city->originalCityname);
}

Before you ask for further variations please read the manual.

Upvotes: 1

Happy Coding
Happy Coding

Reputation: 2525

You can do like this :

if($city->originalCityname)
  $city->originalCityname .= '(Italy)';

If you want that $city->originalCityname contains Rome :

if(strpos($city->originalCityname,'Rome') !== false)
{
    $city->originalCityname .= ' (Italy)';
}

Upvotes: 1

Related Questions