开发者

PHP regex replace white space by   if it is following single letter

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


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.


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) );


<?php

$str = 'your string';

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

?>

Should do the trick.


To preserve the white spaces and line breaks for a text originating from a database:

<pre>
echo nl2br(str_replace(' ','&nbsp', stripslashes( database_string )));
<pre>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜