如何用php中的给定字符串替换带有空格的字符?

时间:2017-03-26 22:44:55

标签: php regex

$country = preg_replace(array('/^\[/','/\]$/'), '',$country); 

这将根据此SO question

删除文本中任何位置的括号

但我们可以说:

United_arab_emirates

我们怎样才能将其作为:

United Arab Emirates

注意:这里不是php大师*

这就是我所拥有并尝试过的(感谢其中一个答案)

$custom_country = usp_get_meta(false, 'usp-custom-3');
$custom_country = htmlspecialchars_decode($custom_country);
$custom_country = nl2br($custom_country);
$country = preg_replace(array('_'), ' ',$country); 
echo ucfirst($custom_country);

结果仍为United_arab_emirates

3 个答案:

答案 0 :(得分:6)

最快的方法是两个步骤:

  1. 用空格替换下划线
  2. 每个单词的大写第一个字母
  3. 代码:

    $country = str_replace('_', ' ', $country);
    $country = ucwords($country);
    

答案 1 :(得分:2)

$country = preg_replace(array('[_]'), ' ',$country); 

或者您可以使用字符串替换

$country = str_replace("_"," ",$country);

答案 2 :(得分:1)

如果_是您需要替换的唯一额外字符,则可以使用str_replace

$country = str_replace("_", " ", $country); 

更多信息:http://php.net/manual/en/function.str-replace.php