簡體   English   中英

PHP正則表達式替換空格,如果它遵循單個字母

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

我有用戶定義的字符串(html格式化的字符串要保存並在web中使用)並且需要找到一種方法來替換單個字母后面的每個空白區域 

例如"this is a string"應該變成"this is a string"

"bla bla bl abla b la blabla"應該成為"bla bla b l abla b la blabla" ......等等......

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

這里的則表達式執行正向lookbehind ,確保空格前面有單個字母和單詞邊界。

沒有正則表達式

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

?>

應該做的伎倆。

要保留源自數據庫的文本的空格和換行符,請執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM