2010-01-19 66 views
4

我有用户定义的字符串(被保存在网页中使用HTML格式化字符串),需要找到一种方式来代替每个空格这是后一个右信由 PHP正则表达式的 代替空格如果下单字母

例如"this is a string"应成为"this is a string"

"bla bla b l abla b la blabla"应该成为"bla bla b l abla b la blabla" ...等...

+1

怎么样的ASCII字母以外的单信吗? ' “AllonsàLa Plage酒店?”' - 甚至' “Allonsà La Plage酒店”' – 2010-01-19 16:17:19

回答

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

正则表达式这里执行positive lookbehind其确保的空间由单一的前面字母和单词边界。

+0

我建议,以取代'\ s'以'\ B',这将在这种情况下工作,'我am' – 2010-01-19 15:55:07

+0

@Ivan :[urgh;我讨厌@]好点。我把'\ s'那里,因为我还在上的想法,在最开始的一个字母不计。但是,这是基于有缺陷的其他假设(和OP的怪异格式谁把空格各地引号...) – Joey 2010-01-19 15:57:09

0
<?php 

$str = 'your string'; 

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

?> 

应该这样做。

2

没有正则表达式

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

要保留从数据库发起文本的空格和换行:

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