I have user defined string (html formated string to be saved and used in web) and need to find a way to replace each white space which is right after a single letter by
preg_replace('/(?<=\b[a-z]) /i', ' ', $s);
The regular expression here performs a positive lookbehind which ensures that the space is preceded by a single letter and a word boundary.
without regex
$str = "this is a string" ;
$s = explode(" ",$str);
foreach ($s as $i => $j){
if (strlen($j)==1){
$s[$i]="$j ";
}
}
print_r ( implode(" ",$s) );
To preserve the white spaces and line breaks for a text originating from a database:
<pre>
echo nl2br(str_replace(' ',' ', stripslashes( database_string )));
<pre>
<?php
$str = 'your string';
$str = preg_replace(array('/ ([a-zA-Z]) /', '/^([a-zA-Z]) /', array(' $1 ', '$1 '), $str);
?>
Should do the trick.