Php:检测由特殊字符包围的字符串中的单个字母


Php: detect single letter in a string surrounded by special characters

假设我有这些字符串

tavern-o-fallon-new-york
cut-n-shoot-texas
cut-n-shoot-texas-at-o-fellon

我想检测 -o- 或任何其他模式的所有出现,并转换为 o'

所以我可以将字符串转换为

Tavern O'Fallon New York
Cut'N'Shoot Texas
Cut'N'Shoot Texas At O'Fellon

我相信我可以使用一些常见的模式数组,如 O'、'N' 等。

我会使用str_replace:

$phrase = 'tavern-o-fallon-new-york
cut-n-shoot-texas
cut-n-shoot-texas-at-o-fellon';
$phrase = str_replace(array('-n-','o-','-'),array('`N`','O`',' '), $phrase);
echo ucwords($phrase);

输出:

Tavern O`fallon New York
Cut`N`shoot Texas
Cut`N`shoot Texas At O`fellon

编辑:

要修复小写字母:

$phrase = str_replace(array('-n-','o-','-'),array('`N` ','O` ',' '), $phrase); // add an extra space after the quote;
$phrase = ucwords($phrase); //then ucfirst can do the job
$phrase = str_replace('` ','`', $phrase); //remove the extra space
echo $phrase;