![](/img/trans.png)
[英]How to correctly replace multiple white spaces with a single white space in 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', ' ', $s);
這里的正則表達式執行正向lookbehind ,確保空格前面有單個字母和單詞邊界。
沒有正則表達式
$str = "this is a string" ;
$s = explode(" ",$str);
foreach ($s as $i => $j){
if (strlen($j)==1){
$s[$i]="$j ";
}
}
print_r ( implode(" ",$s) );
<?php
$str = 'your string';
$str = preg_replace(array('/ ([a-zA-Z]) /', '/^([a-zA-Z]) /', array(' $1 ', '$1 '), $str);
?>
應該做的伎倆。
要保留源自數據庫的文本的空格和換行符,請執行以下操作:
<pre>
echo nl2br(str_replace(' ',' ', stripslashes( database_string )));
<pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.