doudou8783 2016-01-15 20:37
浏览 52
已采纳

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

Please see my code below.

this returns John Doe L. R T

I want it to return 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;
  • 写回答

2条回答 默认 最新

  • duanji1899 2016-01-15 20:46
    关注

    You can use preg_replace for that

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

    The result would be

    John Doe L. R. T.

    And you'll probably want to replace that for uppercase-letters only (since they are likely to be names), so you should not use the i flag.

    preg_replace('/\b\s[A-z]{1}\b/', '$0.', $string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图