用php添加特定字符后的空格 [英] Add a space after a specific character with php

查看:81
本文介绍了用php添加特定字符后的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了谷歌搜索,没有任何帮助。我对PHP没有经验。我希望问题清楚。



所以我想要的是在字符串中的特定字符之后放置空格



类似于:

/ p>

  1234b1 

to:

  1234b 1 

我需要一个代码来为我做这件事



注意:不需要喂我。

解决方案

一个相当优雅的方法是使用正则表达式

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

使用PHP的交互式外壳程序运行此操作:

  $ php -a 
启用交互模式

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

编辑:如果您想跳过一行,你用\ $ 0 \ n更新 $ replacement ,或者如果你想HTML新行: $ 0< br>

  $ input ='abbbbasasjscxxxxc' ; 
$ pattern ='/ c /';
$ replacement =\ $ 0 \\\
; HTML
$ output = preg_replace($ pattern,$ replacement,$ input); //'$ 0< br>'
echo $ output;


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.

解决方案

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\n", or if you want HTML new lines: $0<br>:

$input = 'abbbbasasjscxxxxc';
$pattern = '/c/';
$replacement = "\$0\n"; //'$0<br>' for HTML
$output = preg_replace($pattern,$replacement,$input);
echo $output;

这篇关于用php添加特定字符后的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆