PHP函数大全:常用函数列表及示例操作
PHP语言广泛应用于Web应用程序开发,它支持多种常用函数以及数据结构和算法。这篇文章汇总了一些常用的PHP函数列表,包括字符串、数组、日期、文件系统、HTTP、网络等方面,同时也提供了一些常见的使用示例及操作。
1. 字符串函数
常用字符串函数包括strlen()、strpos()、str_replace()、substr()等等,以下是一些使用示例:
//字符串长度
$str = "Hello World";
echo strlen($str); //11
//查找字符串位置
$str = "Hello World";
echo strpos($str, "World"); //6
//替换字符串
$str = "Hello World";
echo str_replace("World","PHP",$str); //Hello PHP
//截取字符串
$str = "ABCDEFG";
echo substr($str,3,2); //DE
2. 数组函数
常用数组函数包括count()、array_push()、array_pop()、array_shift()等等,以下是一些使用示例:
//数组长度
$arr = array("a","b","c");
echo count($arr); //3
//在数组尾部添加元素
$arr = array("a","b");
array_push($arr,"c");
print_r($arr); //Array ( [0] => a [1] => b [2] => c )
//弹出数组尾部元素
$arr = array("a","b","c");
echo array_pop($arr); //c
//弹出数组头部元素
$arr = array("a","b","c");
echo array_shift($arr); //a
3. 日期函数
常用日期函数包括date()、time()、strtotime()等等,以下是一些使用示例:
//获取当前日期
echo date("Y-m-d"); //2021-06-30
//获取当前时间戳
echo time(); //1625014045
//将时间字符串转换为时间戳
$time = "2021-06-30 12:30:00";
echo strtotime($time); //1625045400
4. 文件系统函数
常用文件系统函数包括file_get_contents()、file_put_contents()、file_exists()、mkdir()等等,以下是一些使用示例:
//读取文件内容
$content = file_get_contents("test.txt");
//写入文件内容
$content = "Hello World!";
file_put_contents("test.txt",$content);
//检查文件是否存在
if(file_exists("test.txt")){
echo "文件存在";
}
//创建目录
mkdir("test");
5. HTTP函数
常用HTTP函数包括header()、curl()、file_get_contents()等等,以下是一些使用示例:
//设置HTTP响应头
header("Content-type: application/json");
//使用curl发送HTTP请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
//使用file_get_contents()发送HTTP请求
$response = file_get_contents("http://example.com");
6. 网络函数
常用网络函数包括socket_create()、socket_bind()、socket_listen()、socket_accept()等等,以下是一些使用示例:
//创建服务器Socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, "127.0.0.1", 8080);
socket_listen($sock);
//接受客户端连接
$client = socket_accept($sock);
//发送数据给客户端
$data = "Hello World!";
socket_write($client, $data, strlen($data));
以上就是一些常用的PHP函数及其使用示例,它们可以满足大多数Web开发需求。如果需要使用更高级的功能,还可以查阅PHP官方文档并学习相关函数的使用方法和参数说明。
