dongshan9338 2015-12-26 15:53 采纳率: 0%
浏览 352
已采纳

使用php在特定字符后添加空格

I tried Googling and nothing helped. I'm inexperienced with PHP. I hope question is clear.

So what I want is to put a space after a specific character in a string

like from:

1234b1

to:

1234b 1

I need a code to do it for me

NOTE: No need to spoon-feed me.

  • 写回答

2条回答 默认 最新

  • douchen2011 2015-12-26 15:57
    关注

    A rather elegant way to do this is using a regex:

    $input = '1234b1';
    $pattern = '/b/';
    $replacement = '$0 ';
    $output = preg_replace($pattern,$replacement,$input);
    

    Running this with PHP's interactive shell:

    $ php -a
    Interactive mode enabled
    
    php > $input = '1234b1';
    php > $pattern = '/b/';
    php > $replacement = '$0 ';
    php > $output = preg_replace($pattern,$replacement,$input);
    php > echo $output;
    1234b 1
    

    EDIT: in case you want to skip a line, you update $replacement with "\$0 ", or if you want HTML new lines: $0<br>:

    $input = 'abbbbasasjscxxxxc';
    $pattern = '/c/';
    $replacement = "\$0
    "; //'$0<br>' for HTML
    $output = preg_replace($pattern,$replacement,$input);
    echo $output;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持