Reputation: 591
Here's my URL:
http://www.mywebsite.com/local/cityname-free-services
I am using
$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper($check);
echo $check;
to get the city name and capitalize it. However, when it echos I am getting this:
CITYNAME-FREE-SERVICES
when all I want to echo is this:
CITYNAME
What do I need to change in the code to just get the city name?
Also, some of the city names have dashes in them and I need those replaced with a blank space when echoed. What needs to be added for that? Thanks!
Upvotes: 1
Views: 314
Reputation: 7773
You want to explode again your resulting string with -
and keep the first element, something along the lines of
$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = current(explode('-', strtoupper($check)));
echo $check;
This way, if the last part changes, you will still have your CITYNAME
valid.
Some more explanation, explode
(documentation here) will break the string into array elements, and it will break it using the first parameter, so in this case, passing -
will create an array with 3 elements, CITYNAME
, FREE
and SERVICES
. current
(documentation here) will take the current position in the array and return this value, by default, the current position is on the first element. You can also index individual elements in your array, so explode('-', strtoupper($check))[0]
would also give you CITYNAME
, and using [1]
and [2]
would give you FREE
and SERVICES
.
Edit: I didn't see the dash part about city names. This complicates a bit the problem as your URL contains other dashes that you want to get rid of. If "-FREE-SERVICES" is constant and that's always the part you want to get rid of, then doing what cale_b suggested is a good idea, which is to replace "free-services"
with ""
. So I'm +1 his answer.
Edit 2: For some reason my answer was picked, for names with dashes you will need to do something similar to what cale_b suggested!
Upvotes: 1
Reputation: 16828
$url = 'http://www.mywebsite.com/local/cityname-free-services';
$check = end(explode('/local/',$url));
$check = strtoupper($check);
echo $check; // prints CITYNAME-FREE-SERVICES
echo '<br>';
$first_element = strtoupper(str_ireplace(array("-free-services","-"),array(""," "),$check));
echo $first_element; // prints CITYNAME
Upvotes: 0
Reputation: 1114
$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper($check);
$check = explode("-", $check);
echo $check[0];
Upvotes: 0
Reputation: 26180
One of several ways. Someone here will probably show you some regular expressions that do a better job, but this will removes the "free services", as well as replaces dashes with spaces:
$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper(str_ireplace("free-services", "", $check));
echo str_replace("-", " ", $check);
Upvotes: 2