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 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下