CHRIS
CHRIS

Reputation: 957

Using Regex to add whitespace

I have a string like this:

text..moretext,moartxt..,asd,,gerr..,gf,erg;ds

Which is basically, variable amounts of text, followed by variable amounts of punctuation, followed by further variable amounts of text and so forth.

How can I convert the above string to this in PHP using Regex?

text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds

Each word may only have 1 character of punctuation on either side of it.

Upvotes: 0

Views: 161

Answers (2)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

Description

I would do this in two passes, first the punctuation after each word. Then a pass for the punctuation before the word.

PHP Code Example:

<?php
$sourcestring="text..moretext,moartxt..,asd,,gerr..,gf,erg;ds";
echo preg_replace('/(\w[.,;])([^\s])/i','\1 \2',$sourcestring);
?>

$sourcestring after replacement:
text. .moretext, moartxt. .,asd, ,gerr. .,gf, erg; ds


<?php
$sourcestring="text. .moretext, moartxt. .,asd, ,gerr. .,gf, erg; ds";
echo preg_replace('/([^\s])([.,;]\w)/i','\1 \2',$sourcestring);
?>

$sourcestring after replacement:
text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds

Upvotes: 2

HamZa
HamZa

Reputation: 14921

Let's solve this with preg_replace_callback:

Code

$string = 'text..moretext,moartxt..,asd,,gerr..,gf,erg;ds';
$chars = '\.,;'; // You need to escape some characters

$new_string = preg_replace_callback('#['.$chars.']+#i', function($m){
    return strlen($m[0]) == 1 ? $m[0].' ':implode(' ', str_split($m[0]));
}, $string); // This requires PHP 5.3+

echo $new_string; // text. .moretext, moartxt. . ,asd, ,gerr. . ,gf, erg; ds

Online demo

Upvotes: 0

Related Questions