0

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.

3
  • Is there a rule for when you put white space between the last of a string of consecutive punctuation and the following letter? In your example sometimes you put a space (e.g., moretext, moartxt) and sometimes you don't (e.g., . ,asd,). If you're consistent, or it doesn't matter, then the answer is very easy. Commented May 25, 2013 at 17:35
  • Priority is given to the earliest word, but if that word already has a letter on the end of it, give it to the next word. I hope this is clear, but it shouldn't matter too much. Commented May 25, 2013 at 17:41
  • Which Language/editor/environment is this in? Commented May 25, 2013 at 18:17

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.