Error
Error

Reputation: 31

Add a space after a specific character with 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.

Upvotes: 1

Views: 3715

Answers (2)

chris85
chris85

Reputation: 23892

I think you can get away with a simple string replace here.

$string = '1234b1';
echo str_replace('b', "b<br>\n", $string);

Output:

1234b
1

Demo: https://eval.in/493496https://eval.in/493503

If the character isn't always a b though you will need a regex.

A regex approach that will replace any alpha character with the character and a new line.

$string = '1234b1';
echo preg_replace('/([a-z])/', '$1' . "<br>\n", $string);

If only ever swapping b replace [a-z] with b. The [] is a character class meaning the characters inside are allowed the a-z is a range of characters.

The <br>s are because it appears you are outputting this in a browser; if not those can be removed. Any non-browser will display the <br> literally.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

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;

Upvotes: 7

Related Questions