如何在PHP字符串中查找任何单个字符并在其末尾添加句号?


How do I look for any lone character in a PHP string and add a period to the end of it?

下面是我要做的一个例子。

我有一个情况,我得到j-doe的查询字符串,我的函数将其更改为J Doe

我怎样才能遍历该字符串,检测到一个孤独的字母(一个名字的初始值),并添加一个句号,使其输出像J. Doe ?

这将需要检测字符串中任何地方的孤独字母,例如将Henry J Doe更改为Henry J. Doe

提前谢谢你!

编辑:字符串是一个来自数据库的名字,所以不需要担心单个字母的单词

这样使用preg_replace:

$str = 'Henry J Doe';
$repl = preg_replace('/([A-Z])(?='s|$)/', ''1.', $str);

实时演示:http://ideone.com/gqVKIG

试试这个…

$str = 'Henry J Doe';
$newWords = array();
$words = explode(' ', $str);
foreach ($words as $word) {
    if (strlen($word) == 1) {
        $word .= '.';
    }
    $newWords[] = $word;
}
$str = implode(' ', $newWords);
echo $str;