PHP7编什么程

php面试基础知识--字符串

2019-05-16  本文已影响0人  沙蒿同学

获取字符串长度

同样是获取字符串长度,但如果你要校验输入中文个数,就得使用此函数了。

<?php
  $str1 = '我是谁';
  echo strlen($str1);  // 9
  echo mb_strlen($str1, 'utf-8');  // 3
  echo mb_strlen($str1, 'gbk');  // 5
  $str2 = 'abc1 ';
  echo strlen($str2);  // 5
  echo mb_strlen($str2, 'utf-8');  // 5
  echo mb_strlen($str2, 'gbk');  // 5

函数返回由字符串组成的数组

<?php
  $str1= "hello";
  $str2= "hello,world";
  var_dump( explode( ',', $str1) ); 
  var_dump( explode( ',', $str2) );
  //以下是结果
  array(1)
  (
      [0] => string(5) "hello"
  )
  array(2)
  (
      [0] => string(5) "hello"
      [1] => string(5) "world"
  )

去除字符串首尾处的空白字符(或者其他字符),字符如下:

" " (ASCII 32 (0x20)),普通空格符。
"\t" (ASCII 9 (0x09)),制表符。
"\n" (ASCII 10 (0x0A)),换行符。
"\r" (ASCII 13 (0x0D)),回车符。
"\0" (ASCII 0 (0x00)),空字节符。
"\x0B" (ASCII 11 (0x0B)),垂直制表符。

<?php
  $text   = "\t\tThese are a few words :) ...  ";
  $binary = "\x09Example string\x0A";
  $hello  = "Hello\t \tWorld";
  echo trim($text);  //These are a few words :) ...
  echo trim($binary);  //Example string
  echo trim($hello);  //Hello           World

将字符串转换为数组

 <?php
  $string = 'HelloWorld';
  var_dump(str_split($string));
  //以下是结果
  array(10) {
  [0]=>
  string(1) "H"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "l"
  [3]=>
  string(1) "l"
  [4]=>
  string(1) "o"
  [5]=>
  string(1) "W"
  [6]=>
  string(1) "o"
  [7]=>
  string(1) "r"
  [8]=>
  string(1) "l"
  [9]=>
  string(1) "d"
  }

<?php
  public hump_to_under($string)
  {
    //要先判断下是否字符串
    $array = str_split($string);
    foreach ($array as $key => &$value) {
        if ($value == '_') {  //已是下划线,跳过
            continue;
        }
        if ($key != 0 && strtoupper($value) === $value) {
            $value = '_' . strtolower($value);
        }
    }
    $re_str = implode('', $array);
    echo $re_str;
  }
上一篇 下一篇

猜你喜欢

热点阅读