酆叔のBlog

  • 首页
  • 分享技术
  • 八卦黑料
  • 生活日常
  • 日记
酆叔のBlog
上辈子作恶多端,这辈子早起上班。
  1. 首页
  2. IT技术
  3. 正文

认识PHP(二)函数

2024年4月12日 694点热度 0人点赞 0条评论

PHP有许多内置函数,同时也支持自定义函数。

<?php
phpinfo(); // 显示当前安装配置的PHP的所有相关信息,(可以查看已经安装的扩展)

# 自定义函数

function greet($name) { // functgreetionName 是函数的名称。$name是函数的参数,可以有零个或多个。 
  echo "Hello, $name!";
} 
greet("John");
字符串处理函数
<?php

# strlen():返回字符串的长度。
$str = "Hello, World!";
$length = strlen($str); // $length = 13

# strpos():查找字符串中某个字符或子串第一次出现的位置。
$str = "Hello, World!";
$pos = strpos($str, "World"); // $pos = 7

# substr():返回字符串的子串。
$str = "Hello, World!";
$sub = substr($str, 7); // $sub = "World!"

# str_replace():替换字符串中的某些字符。
$str = "Hello, World!";
$new_str = str_replace("World", "PHP", $str); // $new_str = "Hello, PHP!"

# strtolower() 和 strtoupper():将字符串转换为小写或大写。
$str = "Hello, World!";
$lower = strtolower($str); // $lower = "hello, world!"
$upper = strtoupper($str); // $upper = "HELLO, WORLD!"

# ucfirst() 和 ucwords() - 分别将字符串的首字母或每个单词的首字母转换为大写。
$str = "hello world!";
$ucfirst = ucfirst($str); // $ucfirst = "Hello world!"
$ucwords = ucwords($str); // $ucwords = "Hello World!"

# trim():去除字符串两端的空格或其他指定字符。
$str = " Hello, World! ";
$trimmed = trim($str); // $trimmed = "Hello, World!"

# explode():将字符串拆分为数组。
$str = "apple,banana,cherry";
$fruits = explode(",", $str); // $fruits = array("apple", "banana", "cherry")

# implode() 或 join() - 将数组元素组合成一个字符串。
$fruits = array("apple", "banana", "orange");
$str = implode(", ", $fruits); // $str = "apple, banana, orange"

# sprintf() - 返回格式化的字符串。
$name = "John";
$age = 30;
$message = sprintf("My name is %s and I am %d years old.", $name, $age); // $message = "My name is John and I am 30 years old."
数组处理函数
<?php

# count():返回数组中的元素数目。
$arr = array(1, 2, 3, 4, 5);
$count = count($arr); // $count = 5

# array_push() 和 array_pop():在数组末尾添加或删除元素。
$arr = array(1, 2, 3);
array_push($arr, 4); // $arr = array(1, 2, 3, 4)
$element = array_pop($arr); // $element = 4, $arr = array(1, 2, 3)

# array_shift() 和 array_unshift():在数组开头添加或删除元素。
$arr = array(1, 2, 3);
array_unshift($arr, 0); // $arr = array(0, 1, 2, 3)
$element = array_shift($arr); // $element = 0, $arr = array(1, 2, 3)

# array_merge():合并一个或多个数组。
$arr1 = array("a", "b");
$arr2 = array("c", "d");
$result = array_merge($arr1, $arr2); // $result = array("a", "b", "c", "d")

# array_slice():从数组中取出一段。$arr = array("a", "b", "c", "d", "e");
$slice = array_slice($arr, 1, 3); // $slice = array("b", "c", "d")

# array_reverse():将数组元素顺序反转。
$arr = array("a", "b", "c", "d");
$reversed = array_reverse($arr); // $reversed = array("d", "c", "b", "a")

# in_array():检查数组中是否存在某个值。
$arr = array("apple", "banana", "cherry");
$is_in_array = in_array("banana", $arr); // $is_in_array = true

# array_search():在数组中搜索给定的值,如果找到则返回相应的键名。
$arr = array("apple", "banana", "cherry");
$key = array_search("banana", $arr); // $key = 1

# array_keys():返回数组中的键名。
$arr = array("a" => "apple", "b" => "banana", "c" => "cherry");
$keys = array_keys($arr); // $keys = array("a", "b", "c")

# array_values():返回数组中的所有值。
$arr = array("a" => "apple", "b" => "banana", "c" => "cherry");
$values = array_values($arr); // $values = array("apple", "banana", "cherry")

# array_unique():移除数组中重复的值。
$arr = array(1, 2, 2, 3, 3, 4);
$unique = array_unique($arr); // $unique = array(1, 2, 3, 4)

# array_filter():用回调函数过滤数组中的元素。
$arr = array(1, 2, 3, 4, 5);
$filtered = array_filter($arr, function($value) 
{
 return $value % 2 == 0; // 返回偶数
}); // $filtered = array(2, 4)
文件处理函数
<?php

# fopen():打开文件或 URL。
$handle = fopen("file.txt", "r"); // 以只读方式打开文件

# fclose():关闭文件指针。
fclose($handle); // 关闭文件指针
# fread():读取文件。
$content = fread($handle, filesize("file.txt")); // 读取文件内容

# fwrite():写入文件。
fwrite($handle, "Hello, World!"); // 写入内容到文件

# file_get_contents():将整个文件读入一个字符串中。
$content = file_get_contents("file.txt"); // 将文件内容读入字符串

# file_put_contents():将一个字符串写入文件。
file_put_contents("file.txt", "Hello, World!"); // 将字符串写入文件

# copy():拷贝文件。
copy("source.txt", "destination.txt"); // 拷贝文件

# rename():重命名文件。
rename("oldname.txt", "newname.txt"); // 重命名文件

# unlink():删除文件。 
unlink("file.txt"); // 删除文件

# mkdir():创建目录。
mkdir("newdir"); // 创建目录

# rmdir():删除目录。
rmdir("newdir"); // 删除目录

# scandir():返回指定目录中的文件和目录的数组。
$files = scandir("directory"); // 获取目录中的文件列表
数学函数
<?php

# abs():返回一个数的绝对值。
$abs = abs(-5); // $abs = 5

# acos():返回一个角度的反余弦。
$angle = acos(0.5); // $angle = 1.0471975511966 (弧度值)

# acosh():返回一个数的反双曲余弦。
$result = acosh(10); // $result = 2.9932228461264

# asin():返回一个角度的反正弦。
$angle = asin(0.5); // $angle = 0.5235987755983 (弧度值)

# asinh():返回一个数的反双曲正弦。
$result = asinh(10); // $result = 2.9982229502978

# atan():返回一个角度的反正切。
$angle = atan(1); // $angle = 0.78539816339745 (弧度值)

# atan2():返回给定的 X 和 Y 坐标值的反正切。
$angle = atan2(4, 3); // $angle = 0.92729521800161 (弧度值)

# atanh():返回一个数的反双曲正切。
$result = atanh(0.5); // $result = 0.54930614433405

# base_convert():在任意进制之间转换数字。
$result = base_convert("1010", 2, 10); // $result = 10 (将二进制转换为十进制)

# bindec():将二进制转换为十进制。
$result = bindec("1010"); // $result = 10

# ceil():将二进制转换为十进制。
$ceil = ceil(4.3); // $ceil = 5

# cos():返回一个角度的余弦。
$result = cos(0); // $result = 1

# cosh():返回一个数的双曲余弦。
$result = cosh(0); // $result = 1

# decbin():将十进制转换为二进制。
$result = decbin(10); // $result = "1010"

# dechex():将十进制转换为十六进制。
$result = dechex(10); // $result = "a"

# decoct():将十进制转换为八进制。
$result = decoct(10); // $result = "12"

# deg2rad():将角度转换为弧度。
$result = deg2rad(180); // $result = 3.1415926535898 (π)

# exp():返回 e 的指定次幂。
$result = exp(1); // $result = 2.718281828459

# expm1():返回 exp(x) - 1,即使 x 的值过大也可以计算出正确结果。
$result = expm1(1); // $result = 1.718281828459

# floor():向下舍入为最接近的整数。
$floor = floor(4.7); // $floor = 4

# fmod():返回除法的浮点数余数。
$result = fmod(5.7, 3); // $result = 2.7

# getrandmax():返回系统所能返回的最大随机值。
$max = getrandmax(); // 返回系统所能返回的最大随机值

# hexdec():将十六进制转换为十进制。
$result = hexdec("a"); // $result = 10

# hypot():计算直角三角形的斜边长度。
$result = hypot(3, 4); // $result = 5

# is_finite():判断是否为有限值。
$result = is_finite(INF); // $result = false

# is_infinite():判断是否为无限值。
$result = is_infinite(INF); // $result = true

# is_nan():判断是否为非数值。
$result = is_nan(NAN); // $result = true

# lcg_value():返回一个介于 0 和 1 之间(包括 0,但不包括 1)的伪随机数。
$result = lcg_value(); // 返回
时间与日期函数

用于处理时间和日期,包括获取当前时间、格式化时间、时间戳转换等。

<?php

# date():格式化日期。
echo date("Y-m-d H:i:s"); // 输出当前日期和时间,格式为:年-月-日 时:分:秒

# time():返回当前 Unix 时间戳。
echo time(); // 输出当前 Unix 时间戳

# strtotime():将任何英文文本的日期或时间描述解析为 Unix 时间戳。
echo strtotime("now"); // 输出当前 Unix 时间戳
echo strtotime("2024-04-10 10:00:00"); // 输出指定日期时间的 Unix 时间戳

# mktime():返回一个日期的 Unix 时间戳。
echo mktime(10, 0, 0, 4, 10, 2024); // 输出指定日期时间的 Unix 时间戳

# strftime():根据本地设置格式化日期和时间。
setlocale(LC_TIME, "zh_CN.utf8"); // 设置本地语言环境为中文
echo strftime("%Y年%m月%d日 %H时%M分%S秒"); // 输出当前日期和时间,格式为:年月日 时分秒

# date_create():返回一个新的 DateTime 对象。
$date = date_create("2024-04-10"); // 创建一个 DateTime 对象

# date_format():格式化 DateTime 对象。
$date = date_create("2024-04-10");
echo date_format($date, "Y-m-d"); // 输出日期,格式为:年-月-日

# date_diff():返回两个 DateTime 对象之间的时间间隔。
$start_date = date_create("2024-04-10");
$end_date = date_create("2024-04-15");
$interval = date_diff($start_date, $end_date);
echo $interval->format("%R%a days"); // 输出时间间隔,格式为:正负号加上天数

# strtotime():将任何英文文本的日期或时间描述解析为 Unix 时间戳。
echo strtotime("now"); // 输出当前 Unix 时间戳
echo strtotime("2024-04-10 10:00:00"); // 输出指定日期时间的 Unix 时间戳

# date_default_timezone_set():设置脚本中所有日期/时间函数使用的默认时区。
date_default_timezone_set('Asia/Shanghai'); // 设置时区为上海
数据验证与过滤函数

用于验证和过滤用户输入数据,包括检查邮箱、URL、数字、过滤 HTML 标签等。

<?php

# filter_var():对变量进行过滤。
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "有效的电子邮件地址";
} else {
    echo "无效的电子邮件地址";
}

# filter_input():从输入获取变量,并对其进行过滤。
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

# filter_var_array():对多个变量进行过滤。
$data = array(
    'email' => 'test@example.com',
    'age' => 30
);
$filters = array(
    'email' => FILTER_VALIDATE_EMAIL,
    'age' => array(
        'filter' => FILTER_VALIDATE_INT,
        'options' => array('min_range' => 1, 'max_range' => 120)
    )
);
$result = filter_var_array($data, $filters);

# filter_input_array():从输入获取多个变量,并对其进行过滤。
$filters = array(
    'email' => FILTER_VALIDATE_EMAIL,
    'age' => array(
        'filter' => FILTER_VALIDATE_INT,
        'options' => array('min_range' => 1, 'max_range' => 120)
    )
);
$result = filter_input_array(INPUT_POST, $filters);

# htmlspecialchars():将特殊字符转换为 HTML 实体。
$str = "<script>alert('Hello');</script>";
echo htmlspecialchars($str);

# strip_tags():从字符串中去除 HTML 和 PHP 标记。
$str = "<p>Hello, <strong>World!</strong></p>";
echo strip_tags($str); // 输出: Hello, World!

# addslashes():在字符串中的单引号、双引号等特殊字符前加上反斜杠。
$str = "It's a good day.";
echo addslashes($str); // 输出: It\'s a good day.

# stripslashes():去除由 addslashes() 函数添加的反斜杠。
$str = "It\'s a good day.";
echo stripslashes($str); // 输出: It's a good day.

# filter_input_array():从输入获取多个变量,并对其进行过滤。
$filters = array(
    'email' => FILTER_VALIDATE_EMAIL,
    'age' => array(
        'filter' => FILTER_VALIDATE_INT,
        'options' => array('min_range' => 1, 'max_range' => 120)
    )
);
$result = filter_input_array(INPUT_POST, $filters);
数据库函数

用于连接数据库、执行 SQL 查询、获取查询结果等数据库操作。

<?php

# 连接数据库 
mysqli_connect() // 连接 MySQL 数据库。
PDO::__construct() // 创建一个新的 PDO 实例以连接到数据库。

# 执行查询 
mysqli_query() // 执行 SQL 查询。
PDO::query() // 执行 SQL 查询并返回 PDOStatement 对象。

# 获取结果 
mysqli_fetch_assoc() // 从结果集中取得一行作为关联数组。
PDOStatement::fetch() // 从结果集中获取下一行。

# 处理结果 
mysqli_num_rows() // 返回结果集中行的数量。
PDOStatement::rowCount() // 返回受上一个 SQL 语句影响的行数。

# 准备语句(预处理) 
mysqli_prepare() // 预处理 SQL 语句。
PDO::prepare() // 准备 SQL 语句以供执行。

# 绑定参数 
mysqli_stmt_bind_param() // 将变量绑定到预处理语句中的参数。
PDOStatement::bindParam() // 绑定一个参数到指定的变量名。

# 执行准备语句 
mysqli_stmt_execute() // 执行准备好的语句。
PDOStatement::execute() // 执行准备好的语句。

# 获取插入 ID 
mysqli_insert_id() // 返回上一次插入操作的 ID。
PDO::lastInsertId() // 返回最后插入行的ID或序列值。

# 错误处理
mysqli_error() // 返回最近调用函数的错误信息。
PDO::errorInfo() // 获取跟数据库句柄上一次操作相关的 SQLSTATE。
网络与文件系统函数

用于执行网络请求等。

<?php

# fsockopen():打开一个 Internet 或 Unix 域套接字连接。
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);

# file():将文件读入数组中。
$lines = file("http://www.example.com/");

# file_get_contents() 和 file_put_contents():与文件系统函数相同,但可用于访问 URL。
$content = file_get_contents("http://www.example.com/");
file_put_contents("file.txt", $content);

# fread() 和 fwrite():与文件系统函数相同,但可用于读写网络套接字。
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n");
$response = fread($fp, 8192);
fclose($fp);

# curl_init()、curl_setopt() 和 curl_exec():用于执行 HTTP 请求,支持更多高级功能。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
图像处理函数

用于生成、处理图像,包括缩放、裁剪、添加水印等操作。

<?php

# 图像创建与加载 
imagecreatefromjpeg()、imagecreatefrompng()、imagecreatefromgif() // 从 JPEG、PNG、GIF 格式的文件

# 创建新的图像资源。
imagecreatefromstring() // 从字符串中创建图像资源。

# 图像保存 
imagejpeg()、imagepng()、imagegif() // 将图像资源保存为 JPEG、PNG、GIF 格式的文件。

# 图像大小调整 
imagescale() // 重新调整图像大小。
imagecopyresampled() // 重采样缩放图像。

# 图像水印 
imagecopy() // 拷贝图像的一部分到另一个图像上。
imagecopymerge() // 拷贝并合并图像的一部分到另一个图像上,支持设置透明度。
imagettftext() // 在图像上绘制 TrueType 字体的文本。

# 图像处理
imagefilter() // 对图像应用滤镜效果,如黑白、模糊等。
imageflip() // 翻转图像。

# 其他
imagedestroy() // 销毁图像资源,释放内存。
imagecolorallocate()、imagecolorallocatealpha() // 分配颜色或颜色带透明度。
<?php

例:
$image = imagecreatefromjpeg("example.jpg");// 创建新图像资源并加载图像文件
imagepng($image, "example.png");// 将图像保存为 PNG 格式
$thumb = imagescale($image, 100, 100);// 调整图像大小

$watermark = imagecreatefrompng("watermark.png");
imagecopymerge($image, $watermark, 10, 10, 0, 0, imagesx($watermark), imagesy($watermark), 50);// 在图像上添加水印

header('Content-Type: image/png');/
imagepng($image);/ 输出图像到浏览器

imagedestroy($image);
imagedestroy($thumb);// 销毁图像资源
XML 与 JSON 处理函数

用于解析和生成 XML 和 JSON 格式的数据。

<?php

# simplexml_load_string() // 将 XML 字符串转换为 SimpleXMLElement 对象。
$xmlString = "<root><name>John</name></root>";
$xml = simplexml_load_string($xmlString);

# simplexml_load_file() // 加载 XML 文件并将其转换为 SimpleXMLElement 对象。
$xml = simplexml_load_file("data.xml");

# DOMDocument() // 创建一个新的 DOMDocument 对象,用于创建、解析和操作 XML 文档。
$doc = new DOMDocument();

# DOMXPath() // 在 DOM 文档中执行 XPath 查询。
$xpath = new DOMXPath($doc);

# $element->addChild() // 在 XML 元素下添加子元素。
$child = $xml->addChild("age", "30");

# $element->attributes() // 获取 XML 元素的属性。
$attributes = $xml->name->attributes();

# json_encode() // 将 PHP 值转换为 JSON 字符串。
$data = array("name" => "John", "age" => 30);
$jsonString = json_encode($data);

# json_decode() // 将 JSON 字符串转换为 PHP 对象或数组。
$jsonData = '{"name":"John","age":30}';
$data = json_decode($jsonData);

# file_get_contents() 和 file_put_contents() // 用于读取和写入 JSON 文件。
$jsonString = file_get_contents("data.json");
file_put_contents("data.json", $jsonString);
加密与安全函数

用于加密解密数据、生成哈希值、验证密码等安全相关操作。

<?php

# md5() // 计算字符串的 MD5 散列值。
$hash = md5("password");

# sha1() // 计算字符串的 SHA-1 散列值。
$hash = sha1("password");

# password_hash() // 创建密码的哈希。
$hash = password_hash("password", PASSWORD_DEFAULT);

# password_verify() // 验证密码与哈希是否匹配。
if (password_verify($password, $hash)) {
echo "密码正确";
} else {
echo "密码错误";
}

# base64_encode() // 对字符串进行 Base64 编码。
$encoded = base64_encode("Hello, World!");

# base64_decode() // 对 Base64 编码的字符串进行解码。
$decoded = base64_decode($encoded);

# openssl_encrypt() // 使用 OpenSSL 加密数据。
$encrypted = openssl_encrypt("Hello, World!", "AES-128-CBC", $key, 0, $iv);

# openssl_decrypt() // 使用 OpenSSL 解密数据。
$decrypted = openssl_decrypt($encrypted, "AES-128-CBC", $key, 0, $iv);

# htmlspecialchars() // 将特殊字符转换为 HTML 实体。
$encoded = htmlspecialchars($string);

# filter_var() // 过滤变量。
$filtered = filter_var($email, FILTER_SANITIZE_EMAIL);
错误处理函数

用于捕获和处理 PHP 运行时产生的错误和异常。

# error_reporting() // 设置 PHP 的错误报告级别。
error_reporting(E_ALL);

# ini_set() // 在运行时设置 PHP 配置选项。
ini_set('error_reporting', E_ALL);

# error_log() // 将错误消息记录到错误日志中。
error_log("Error message", 3, "/var/log/php_errors.log");

# try...catch // 捕获和处理异常。
try {
// 可能抛出异常的代码
} catch (Exception $e) {
// 异常处理代码
}

# set_exception_handler() // 设置用于捕获未捕获异常的自定义异常处理程序。
function customExceptionHandler($e) {
// 自定义异常处理代码
}
set_exception_handler("customExceptionHandler");

# set_error_handler() // 设置自定义错误处理函数。
function customErrorHandler($errno, $errstr, $errfile, $errline) {
// 自定义错误处理代码
}
set_error_handler("customErrorHandler");

# trigger_error() // 触发用户自定义的错误消息。
trigger_error("Error message", E_USER_ERROR);

# assert() // 断言某个条件为真,如果条件为假则触发断言异常。
assert($var == 1);
标签: PHP
最后更新:2024年4月12日

酆叔

上辈子作恶多端,这辈子早起上班。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

最新 热点 随机
最新 热点 随机
2025/05/15 周四 晴 2025/05/12 周一 晴 2025/05/08 周四 多云 2025/05/07 周三 阵雨 2025/05/06 周二 阵雨 2025/04/30 周三 多云
2025/04/27 周日 阴2025/04/28 周一 阵雨2025/04/29 周二 晴2025/04/30 周三 多云2025/05/06 周二 阵雨2025/05/07 周三 阵雨
认识PHP(三)超全局变量数组 策略模式 2025/05/15 周四 晴 认识GO语言 PHP 抽象类 校园霸凌
腾讯云
又拍云
订阅
订阅

COPYRIGHT © 2024 酆叔のBlog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备2023016219号