[PHP字符串]②--花括号{}的作用

[PHP字符串]②--花括号{}的作用_第1张图片
Paste_Image.png
$username = 'king';
//echo "my name is $kings";
echo "my name is {$username}s";//my name is kings
echo "
"; echo "my name is ${username}s";//my name is kings
Paste_Image.png
[PHP字符串]②--花括号{}的作用_第2张图片
Paste_Image.png

查询 修改

$str = 'abcdef';
echo $str{0};//a
echo "
"; $str{1} = 'm'; echo $str;//amcdef echo "
"; //只能用一个字符修改一个字符 $str{4} = 'hello'; echo $str;//amcdhf echo "
"; //中文在UTF8下占三个字符 $str = "你好"; echo $str{0}; echo $str{1}; echo $str{2};//你
Paste_Image.png

删除

$str = "imooc";
$str{1} = '';
echo $str . "
"; //iooc var_dump($str); //string 'i�ooc' (length=5)
Paste_Image.png

添加

$str = 'abc';
$str{3} = 'def';
echo $str . "
";//abcd $str{5} = "fgh"; echo $str . "
";//abcd f var_dump($str);//string 'abcd f' (length=6)
Paste_Image.png

[]与{}效果相同

$str = 'hello';
echo $str[0] . "
";//h $string = 'sdsdsdsdkjfkgjfjkgfj'; echo $string{mt_rand(0, strlen($string) - 1)};//g
Paste_Image.png

思考:产生4位验证码

你可能感兴趣的:([PHP字符串]②--花括号{}的作用)