1

这是我的网址:

http://www.mywebsite.com/local/cityname-free-services

我在用

$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper($check);
echo $check;

获取城市名称并将其大写。但是,当它回响时,我得到了这个:

CITYNAME-FREE-SERVICES

当我想要回应的是:

CITYNAME

我需要在代码中更改什么才能获得城市名称?

此外,一些城市名称中有破折号,我需要在回显时将它们替换为空格。为此需要添加什么?谢谢!

4

4 回答 4

2

几种方式之一。这里有人可能会向您展示一些做得更好的正则表达式,但这会删除“免费服务”,并用空格替换破折号:

$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper(str_ireplace("free-services", "", $check));
echo str_replace("-", " ", $check);
于 2012-11-24T22:48:21.130 回答
1

你想再次爆炸你的结果字符串-并保留第一个元素,类似于

$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = current(explode('-', strtoupper($check)));
echo $check;

这样,如果最后一部分发生了变化,你仍然有你的CITYNAME有效。

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!

于 2012-11-24T22:49:53.130 回答
0
$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
于 2012-11-24T22:49:33.973 回答
0
$url = $_SERVER['REQUEST_URI'];
$check = end(explode('/local/',$url));
$check = strtoupper($check);
$check = explode("-", $check);
echo $check[0];
于 2012-11-24T22:51:19.223 回答