user3741635
user3741635

Reputation: 862

How to replace "," with ", "?

I want to replace "Some Sentence,Some Sentence" in a string with "Some Sentence,[Space]Some Sentence".

I tried str_replace(",", ", ",$str), but the problem is that this replace both "," and ",[Space]" creating ",[Space]" and ",[Space][Space]". Is there a way to replace only the comma that comes exactly between two Sentences?

I hope you understand what I mean.

Upvotes: 0

Views: 109

Answers (4)

nhahtdh
nhahtdh

Reputation: 56809

Alternatively, you can use a negative look-ahead to check that the character following a , is not a whitespace character before replacing it with :

$str = "begin,space, no sp,   not space,space,,~~~,@@##$,end";
$str = preg_replace('/,(?!\s)/', ", ", $str);

Output: begin, space, no sp, not space, space, , ~~~, @@##$, end

Demo on regex101

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

If the delimiter is consistent, you could also leverage straight string operations:

$foo = "Something,Something";
$bar = implode(", ", explode(",", $foo));

explode creates an array, using the delimiter as a token. implode concatenates it back using the new delimiter.

note: this would not take into account scenarios where spaces (and other characters) are significant. But is a simple alternative.

Upvotes: 1

chris85
chris85

Reputation: 23892

You could do something like this:

$string = 'Some Sentence,Some Sentence don\'t touch, this one but,thisone do, also';
echo preg_replace('~,([^\s])~', ', $1', $string);

That says find a comma , without a whitespace as the next character [^\s]. The [] is a character class listing characters and the ^ makes it a negative search. The ~s are delimiters telling where the regex starts and ends.

Update: The () captures the non-whitespace character and returns it with the , and space.

The \s is any white space character (tab, newline, space). If you only want space change that to \h which is a horizontal space.

Regex101 demo: https://regex101.com/r/eU1iR1/2

Update:

An alternative approach:

$string = 'Some Sentence,Some Sentence don\'t touch, this one but,thisone do, also';
    echo preg_replace('~,\s(*SKIP)(*FAIL)|,~', ', ', $string);

which says if it finds a comma with whitespace first skip it otherwise add the comma with a whitespace. Here's an article on that approach, http://www.rexegg.com/regex-best-trick.html.

Demo:https://regex101.com/r/eG8jS8/1

Upvotes: 1

SimZal
SimZal

Reputation: 301

Another way would be to do it like this:

$str = str_replace(", ", ",", $str);
$str = str_replace(",", ", ",$str);

While regex solution is more powerful (it works on unlimited spaces), this one is perhaps more newbie friendly.

Upvotes: 0

Related Questions