php常用字符串长度函数strlen()与mb_strlen()用法实例分析

yipeiwu_com6年前PHP代码库

本文实例讲述了php常用字符串长度函数strlen()与mb_strlen()用法。分享给大家供大家参考,具体如下:

int strlen ( string $string )

int strlen ( string $string )  获取给定字符串的[字节]长度 成功则返回字符串$string的长度,如果$string为空,则返回 0。

<?php
  $str1 = "abcdef";    //输出6
  $str2 = " ab cd ";    //输出7,注意,开头、结尾、中间的空格
  $str3 = "中国你好";    //输出12,但会变化,与系统所采用的字符编码方式有关
  $str4 = "中国,你好";  //输出15,但会变化,与系统所采用的字符编码方式有关
  echo '$str1的字节长度为:'.strlen($str1).'$str2的字节长度为:'.strlen($str2).'';
  echo "<br/>";
  echo '$str3的字节长度为:'.strlen($str3).'$str4的字节长度为:'.strlen($str4).''; 
?>

运行结果:

$str1的字节长度为:6$str2的字节长度为:7
$str3的字节长度为:8$str4的字节长度为:10

mb_strlen() — 获取字符串的长度

mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )

$str 要检查长度的字符串

$encoding,可指定字符编码,如省略则使用内部字符编码

返回值:返回具有encoding编码的字符串str包含的[字符数],多字节的字符被计为 1

<?php
  $str1 = "abcdef";    //输出6
  $str2 = " ab cd ";    //输出7    注意,开头、结尾、中间的空格
  $str3 = "中国你好";    //输出4
  $str4 = "中国,你好";  //输出5
  echo '$str1的字符长度为:'.mb_strlen($str1,"utf-8").'$str2的字符长度为:'.mb_strlen($str2,"utf-8").'';
  echo "<br/>";
  echo '$str3的字符长度为:'.mb_strlen($str3,"utf-8").'$str4的字符长度为:'.mb_strlen($str4,"utf-8").'';
?>

运行结果:

$str1的字符长度为:6$str2的字符长度为:7
$str3的字符长度为:3$str4的字符长度为:5

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php常用函数与技巧总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP实现的统计数据功能详解

PHP实现的统计数据功能详解

本文实例讲述了PHP实现的统计数据功能。分享给大家供大家参考,具体如下: 统计,就是把基本的数据,整合起来。 用到sql的,有group by 功能,count功能,order by功能...

php计算到指定日期还有多少天的方法

本文实例讲述了php计算到指定日期还有多少天的方法。分享给大家供大家参考。具体如下: function countdays($d) { $olddate = substr($d,...

学习使用curl采集curl使用方法

复制代码 代码如下: <?php $cookie_jar = tempnam('./tmp','cookie'); $ch = curl_init(); curl_setopt($...

php基于curl重写file_get_contents函数实例

本文实例讲述了php基于curl重写file_get_contents函数。分享给大家供大家参考,具体如下: file_get_contents在连接不上的时候会提示Connection...

php将print_r处理后的数据还原为原始数组的解决方法

PHP print_r方法可以把变量打印显示,使变量易于理解。如果变量是string,integer或float,将打印变量值本身,如果变量是array,将会按照一定格式显示键和元素。o...