【问题标题】:How can I match characters in a string and place a dot next to each character using regex如何匹配字符串中的字符并使用正则表达式在每个字符旁边放置一个点
【发布时间】:2016-01-15 20:37:50
【问题描述】:

请在下面查看我的代码。

返回 John Doe L. R T

我希望它返回 John Doe 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;

【问题讨论】:

    标签: php regex preg-replace preg-match str-replace


    【解决方案1】:

    您可以为此使用preg_replace

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

    结果是

    John Doe L.R.T.

    您可能只想将其替换为大写字母(因为它们可能是名称),因此您不应使用 i 标志。

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

    【讨论】:

      【解决方案2】:

      您可能只是使用preg_replace() 组合这些操作。像这样的东西应该可以工作:

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

      请注意,您的角色类中有两个小写的z,因此如果您修复了这个问题,则不需要i 修饰符。此外,无需指定{1}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 1970-01-01
        • 2019-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        相关资源
        最近更新 更多