PHP的底层由C语言编写,是一种运行在服务器端解释执行的脚本语言,具有以下几个特性:
1.由于不需要编译,其变量类型在运行时进行创建和确定,是一种弱类型语言
2.PHP代码可以和HTML代码互相嵌套,易于学习和开发
##基本语法
注释方式
变量定义
1 2 3 4 5 6 7 8 9
|
$a; var_dump($a); $a=1;
$b=1.5; $c=$a+$b; echo $c;
|
变量作用域
- PHP的变量有三种作用域local,global,static
- 默认作用域
1 2 3 4 5 6 7 8 9 10 11 12
| $d=1; function scope() { $e=2; echo $e; echo $d; } scope(); echo $d; echo $e;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $f=5; $g=6; function global_test() { global $f,$g; echo $f; echo $g; } global_test();
function globals_test(){ echo $GLOBALS['f']; echo $GLOBALS['g']; } globals_test();
|
1 2 3 4 5 6 7 8 9 10 11 12
| function static_test(){ static $h=0; echo $h; $h++; } static_test(); static_test(); static_test(); static_test();
echo $h;
|
输出方式
1 2 3 4 5 6 7 8 9
|
echo "a","b","c";
$i=3; echo "i=$i";
$arr=array(1,2,3); echo "arr[0]={$arr[0]}";
|
1 2 3
| $j=print "i=$i"; print $j;
|
数据类型
var_dump(变量);函数输出变量的类型和值,非十进制自动转为十进制,字符串类型输出变量长度和值
整型
PHP不支持无符号整数(一个整数占用四个字节,一个字节占8bit,PHP整数二进制的最高位只能表示符号,0表示整数,1表示负数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| echo PHP_INT_SIZE;
echo PHP_INT_MAX;
echo "<br/>"; $a=12; var_dump($a); $b=1.5; var_dump($b); $c=053; var_dump($c); $d=0x5a; var_dump($d);
|
浮点型
字长与平台相关,通常最大值为1.8e308,精度是14
小数的精度从左边第一个非零数开始算起
1 2 3 4 5
| $e=2.4e3; var_dump($e); $f=8E-5; var_dump($f);
|
bool类型
以下值也会被当做false对待:整型0,浮点数0.0,空字符串,字符串”0”,空数组,NULL
1 2 3 4
| $is_true=true; $is_true=false; var_dump($is_true);
|
数组
1 2 3
| $arr = array('a', 'b'); var_dump($arr);
|
字符串类型
单双引号均可
双引号:$表示变量,\表示转移符
单引号:仅输出$符号,仅输出\符号
单引号只解析单引号,双引号只解析双引号
1 2 3
| $txt2='string2'; var_dump($txt2);
|
NULL值
对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Car { var $color; function __construct($color="green") { $this->color = $color; } function what_color() { return $this->color; } } $g=new Car("white"); echo $g->what_color(); var_dump($g);
|
字符串函数
计算字符串长度
strlen函数,返回字符串长度
字符串匹配检索
返回找到匹配串的下标(从0开始),找不到返回false,可选项第三个参数可以限定开始检索的位置
1 2 3 4 5 6 7 8 9 10
| $txt="hello worLd."; $find = strpos($txt, "a"); if($find) { echo "find"; }else { echo "not_find"; }
|
1 2 3 4
| $txt="hello worLd.";
echo strpos($txt, "l");
|
1 2 3 4
| $txt="hello worLd.";
echo strrpos($txt, "l");
|
1 2 3 4
| $txt="hello worLd.";
echo strripos($txt, "l");
|
字符串检索替换
str_ireplace不区分大小写,str_replace区分大小写
1 2 3 4 5 6 7 8 9 10
| $txt="hello worLd."; $txt = str_ireplace('l', '233', $txt); echo $txt;
$color = array('red' , 'blue' , 'black'); $color2 = str_ireplace('red', 'yellow', $color , $index); echo $color2[0]; echo $index;
|
字符串相似度匹配
1 2 3 4
|
similar_text("Hello World","Hello Shanghai",$percent); echo "$percent%";
|
比较字符串大小
strcmp区分大小写,strcasecmp不区分大小写
- =0 - 如果两个字符串相等
- <0 - 如果 string1 小于 string2
- >0 - 如果 string1 大于 string2
1 2
| echo strcmp("Hello world!","Hello world!");
|
字符串拆分
1 2 3 4
| $city="北京 上海 天津 西安 武汉"; $city_arr=explode(" ", $city); print_r($city_arr);
|