dqy0707 2016-06-09 05:50
浏览 126

Php在字符串(正则表达式)中放置一个空格,留下第一个出现的空格

how do i add space before capital letters but leaving the first occurence of capital letter

my string is "MyHomeIsHere" i want it to be "My Home Is Here"...but with the code below i get as " My Home Is Here" space gets added before M too

$String = 'ThisWasCool';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
  • 写回答

4条回答 默认 最新

  • dongpang2029 2016-06-09 06:22
    关注

    As an answer using @SebastianProske's expression with explanations and a demo link to ideone:

    <?php
    
    $string = 'MyHomeIsHere';
    $regex = '~     # delimiters
            \B      # match where \b (a word boundary) does not match
            [A-Z]   # one of A-Z
            ~x';        # free spacing mode for this explanation
    
    $words = preg_replace($regex, ' $0', $string);
    echo $words;
    # output: My Home Is Here
    
    ?>
    

    See it working on ideone.com.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度