方法:1、用str_replace(),语法“str_replace(" "," ",$str)”;2、用preg_replace()配合正则表达式,语法“preg_replace('/\s+/'," ",$str)”。

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

nbsp空格符

在HTML中, 是一个空格实体,又称不换行空格,是最常见和我们使用最多的空格,大多数的人可能只接触了 ,它是按下space键产生的空格。在HTML中,如果你用空格键产生此空格,空格是不会累加的(只算1个)。要使用html实体表示才可累加,

php将空格转换成nbsp符的方法

  • 使用 str_replace() 函数

  • 使用 preg_replace() 函数

1、使用 str_replace() 函数

<?php
header('content-type:text/html;charset=utf-8');   
$str= 'This is a programming tutorial !';
echo $str."<br>";
$newStr = str_replace(" ", "&nbsp;", $str); 
echo $newStr;
?>

1.png

2、使用 preg_replace() 函数

利用preg_replace() 函数配合正则表达式“/\s+/”来替换。

<?php
header('content-type:text/html;charset=utf-8');   
$str= ' 欢迎 来到 PHP中文网 !';
echo $str."<br>";
$newStr = preg_replace('/\s+/', "&nbsp;", $str); 
echo $newStr;
?>

2.png


php怎么将空格转换成nbsp符