如何匹配字符串中的字符并使用正则表达式在每个字符旁边放置一个点

How can I match characters in a string and place a dot next to each character using regex

请看下面我的代码。

这个returns 李四 L. R T

我想要它 return 李四 L.R.T.

$string = "John Doe L R T";

$matches = null;
preg_match('/\b\s[a-zA-z]{1}\b/i', $string, $matches);

foreach ($matches as $match)
{
    $string = str_replace($match, $match.'.',$string);
}

echo $string;

你可以使用 preg_replace

preg_replace('/\b\s[a-zA-z]{1}\b/i', '[=10=].', $string);

结果会是

John Doe L. R. T.

您可能只想将其替换为 uppercase-letters(因为它们很可能是名称),因此您不应使用 i 标志。

preg_replace('/\b\s[A-z]{1}\b/', '[=11=].', $string);

您或许可以使用 preg_replace() 组合这些操作。这样的事情应该有效:

$string = preg_replace('/\b([a-zA-Z])\b/', '.', $string);

请注意,您的字符 class 中有两个小写字母 z,因此如果您修复它,则不需要 i 修饰符。此外,无需指定 {1}.