tags:

views:

498

answers:

4

Hi, 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  .

For example "this is a string" should become "this is a string",

"bla bla b l abla b la blabla" should become "bla bla b l abla b la blabla" ...etc...

+5  A: 
preg_replace('/(?<=\b[a-z]) /i', '&nbsp;', $s);

The regular expression here performs a positive lookbehind which ensures that the space is preceded by a single letter and a word boundary.

Joey
I suggest to replace `\s` with `\b`, which will work in this case `i am`
Ivan Nevostruev
@Ivan: [urgh; I hate the @] Good point. I put `\s` there because I was still on the idea that a single letter at the very start doesn't count. But that was based on flawed other assumptions (and the weird formatting of the OP who put spaces all around the quotation marks ...)
Joey
A: 
<?php

$str = 'your string';

$str = preg_replace(array('/ ([a-zA-Z]) /', '/^([a-zA-Z]) /', array(' $1&nbsp;', '$1&nbsp;'), $str);

?>

Should do the trick.

anomareh
+1  A: 

without regex

$str = "this is a string" ;
$s = explode(" ",$str);
foreach ($s as $i => $j){
    if (strlen($j)==1){
        $s[$i]="$j&nbsp;";
    }
}
print_r ( implode(" ",$s) );
ghostdog74
A: 

to preserve white spaces and line breaks for a text originating from database

echo nl2br(str_replace(' ','&nbsp', stripslashes( database_string )));