Yasmin French
Yasmin French

Reputation: 1282

str_replace leaving whitespace PHP

This is my variable to be altered:

$last = 'Some string 1 foobar'

and my replace statement

$last = str_replace(['1', '2'], '', $last);

and finally the output

Some string   foobar

How do i get rid of the whitespace in between 'string' and 'foobar', my initial thought was that in my str_replace statement using '' as the replacement would also remove the whitespace but it doesnt.

To clarify I want to know how to make it Some string foobar and not Some stringfoobar.

Upvotes: 1

Views: 587

Answers (2)

nicholasnet
nicholasnet

Reputation: 2287

If you do not want to use preg_replace then you can do something like this.

$result = 'Some string 1 foobar';
$result = str_replace(['1', '2'], '', $result);
$result = str_replace('  ', ' ', $result);

However I have to admit that I like preg_replace solution more. Not sure about the benchmark though.

Upvotes: 0

arkascha
arkascha

Reputation: 42984

A regular expression based approach is more flexible for such stuff:

<?php
$subject = 'Some string 1 foobar';
var_dump(preg_replace('/\d\s?/', '', $subject));

The output of above code is: string(18) "Some string foobar"

What does that do, how does it work? It replaces a pattern, not a fixed, literal string. Here the pattern is: any digit (\d) along with a single, potentially existing white space character (\s?).


A different, alternative approach would be that:

<?php
$subject = 'Some string 1 foobar';
var_dump(preg_replace('/(\s\d)+\s/', ' ', $subject));

This one replaces any sequence consisting of one or more occurrences of a digit preceded by a white space ((\s\d)+) along with a single white space by a single white blank character.

Upvotes: 1

Related Questions