php中清除文章中所有空格程序
来源:程序员人生 发布时间:2013-11-16 04:53:25 阅读次数:2881次
清除字符串中空白或空格我们可以使用ereg_replace函数进行替换了,下面给大家整理了一个页面希望对各位有帮助.
去除所有空白,代码如下:
- function delete($str) {
- $str = trim($str);
- $str = ereg_replace("\t","",$str);
- $str = ereg_replace("\r\n","",$str);
- $str = ereg_replace("\r","",$str);
- $str = ereg_replace("\n","",$str);
- $str = ereg_replace(" ","",$str);
- return trim($str);
- }
去除所有注释用preg_replace()函数把注释替换成空(是空,不是空格).去掉字符串中的空格 str_replace(' ','',$cat_name),代码如下:
- $str = ” This line contains\tliberal \r\n use of whitespace.\n\n”;
- $str = trim($str);
- $str = preg_replace(’/\s(?=\s)/’, ‘’, $str);
- $str = preg_replace(’/[\n\r\t]/’, ‘ ‘, $str);
使用上面的例子可以去掉所有多余的空格,首先使用TRim()去头尾空格,接着用preg_replace()去掉重复的空格,当中的(?=)表示只匹配后面的空格跟随前面的空格的空格.代码如下:
- <?php
- $str1=" tt 七夕快乐!nr";
-
-
- echo trim($str1)."<br>";
-
- echo trim($str1," tt")."<br>";
-
- $str2="... 情人节快乐!... 中国...";
-
- echo trim($str2)."<br>";
-
-
- echo ltrim($str2,".")."<br>";
-
-
- echo rtrim($str2,".")."<br>";
- ?>
- <?php
- echo substr("today is father day!",0)."<br>";
- echo substr("today is father day!",6,2)."<br>";
- echo substr("today is father day!",-5,5)."<br>";
- echo substr("today is father day!",0,-5)."<br>";
- echo substr("today is father day!",-5,-1)."<br>";
- ?>
补充一个:php注释和去除空格,代码如下:
-
-
-
-
-
- function strip_whitespace($content) {
- $stripStr = '';
-
- $tokens = token_get_all($content);
- $last_space = false;
- for ($i = 0, $j = count($tokens); $i < $j; $i++) {
- if (is_string($tokens[$i])) {
- $last_space = false;
- $stripStr .= $tokens[$i];
- } else {
- switch ($tokens[$i][0]) {
-
- case T_COMMENT:
- case T_DOC_COMMENT:
- break;
-
- case T_WHITESPACE:
- if (!$last_space) {
- $stripStr .= ' ';
- $last_space = true;
- }
- break;
- case T_START_HEREDOC:
- $stripStr .= "<<<THINK\n";
- break;
- case T_END_HEREDOC:
- $stripStr .= "THINK;\n";
- for($k = $i+1; $k < $j; $k++) {
- if(is_string($tokens[$k]) && $tokens[$k] == ';') {
- $i = $k;
- break;
- } else if($tokens[$k][0] == T_CLOSE_TAG) {
- break;
- }
- }
- break;
- default:
- $last_space = false;
- $stripStr .= $tokens[$i][1];
- }
- }
- }
- return $stripStr;
- }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠