博客列表 >字符串创建方式-php16课7.9

字符串创建方式-php16课7.9

希望
希望原创
2020年07月10日 13:35:21645浏览

一、字符串4种创建方式


1. 单引号’’来创建字符

  1. $str = 'String';
  • 单引号中的变量不能解析
    1. echo 'this is a $str hello';
  • 在变量两边加. $str .可以解析
    1. echo 'this is a ' . $str . ' hello';
  • 单引号中的特殊字符不能解析
    1. echo 'hello \n\r world';
  • 单引号里面出现单引号,视为定界符或单引号,需要转译,加\
    1. echo 'php.\'cn\'';
  • 如果不转译,在单引号里使用双引号
    1. echo 'php."cn"';
  • 输出反斜线\ 要连续写2个,\
    1. echo 'php."cn"\\';

2. 双引号””来创建字符

  • 双引号中的变量能解析
    1. echo "this is a $str";
  • 或者将变量括{}起来,也可以
    1. echo "this is a ${str}123";
  • 双引号可以解析特殊字符
    1. echo "hello \n\r world";
  • 输出反斜线\,也是写2个,\
    1. echo "hello \n\r world\\";

3. heredoc <<< 可以看作是双引号字符串的Plus+

  • heredoc中的字符串不需要双引号定界符,适合html+php混编,写模板
    1. $hello = 'php.cn';
    2. echo <<< HELLO
    3. hello <span style="color:red">$hello</span>
    4. HELLO;

4. nowdoc:可以看作是单引号字符串的Plus+

  • nowdoc 输出的内容不用单引号包裹
    1. echo '<hr>';
    2. echo <<< 'NOW'
    3. this is a String
    4. NOW;

    二、字符串举例,打印输出函数,下面有4种方式


1. printf() 将输出的字符串按指定的格式模板输出

  1. printf('hello %s', 'world');
  2. printf('price: %d', 99);

2. vprintf()的功能与printf()一样,参数不同

  1. vprintf('SELECT * FROM `%s` LIMIT %d', ['staffs', 20]);

3. sprintf() 返回格式化字符串,而不是输出

  1. $sql = sprintf('SELECT * FROM `%s` LIMIT %d', 'staffs', 30);
  2. echo $sql;
  3. file_put_contents('temp.txt', $sql);

4. vsprintf() 与sprintf()功能相同,参数不同

  1. $sql = vsprintf('SELECT * FROM `%s` LIMIT %d', ['staffs', 34]);
  2. echo $sql;
  3. file_put_contents('temp.txt', $sql);

三、分割,查询,替换


1. 数组—->字符串,implode()将数组拼装成一个字符串

  1. echo implode('--', ['html', 'css', 'js', 'php']);

2. 字符串—->数组,explode(),连接数据库

  1. print_r(explode(', ', 'localhost, root, root, uft8, 3306'));

3. list将索引数组中的元素解析到独立变量中,php要7.0以上

  1. list($host, $username, $password) = explode(', ', 'localhost, root, root, uft8, 3306', 4);
  2. echo "host={$host}, username={$username}, password={$password}";

4. 求字串substr,str_pad()

  • 将字符串填充到指定长度str_repeat
    1. echo str_repeat('---|', 10);
  • 字符串替换str_replace
    1. echo str_replace('php', '*', 'php.cn,php,thinkphp', $count);
  • 用特殊字符替换
    1. $search = ['交友', '广告', '直播', '网红'];
    2. echo str_replace($search, ['***', '===', '&&&', '+++'], '广告代理,直播在线,交友互动,网红大咖');

5. trim,从二边删除指定字符

  • 里面有空格,需要删除
    1. $str = ' this is a string';
    2. echo strlen(trim($str));
  • 左右两边的12去掉
    1. $str = '124484php.cn php中文网 this is ljljl444812';
    2. echo trim($str, '12');
  • 去掉里面的数字
    1. echo trim($str, '1..9');

6. strpos,查询is是否出现

  1. echo strpos('this is a test', 'is');

7. strstr,查询字符串首次出现的位置,并反馈

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议