字符串截取函数
function truncateString($string, $length, $suffix = '...') {
if (mb_strlen($string) <= $length) {
return $string;
} else {
return mb_substr($string, 0, $length) . $suffix;
}
}
$text = "这是一段很长的文本...";
$truncatedText = truncateString($text, 10);
echo $truncatedText;
数组去重函数
function uniqueArray($array) {
return array_values(array_unique($array));
}
$numbers = [1, 2, 3, 2, 4, 3, 5];
$uniqueNumbers = uniqueArray($numbers);
print_r($uniqueNumbers);
生成随机字符串函数
function generateRandomString($length = 8) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$randomString = generateRandomString(10);
echo $randomString;
加密和解密函数
function encrypt($data, $key) {
$encryptedData = openssl_encrypt($data, 'AES-128-CBC', $key, 0, substr(md5($key), 0, 16));
return base64_encode($encryptedData);
}
function decrypt($encryptedData, $key) {
$encryptedData = base64_decode($encryptedData);
return openssl_decrypt($encryptedData, 'AES-128-CBC', $key, 0, substr(md5($key), 0, 16));
}
$data = 'Hello, World!';
$key = 'secretkey';
$encryptedData = encrypt($data, $key);
$decryptedData = decrypt($encryptedData, $key);
echo $encryptedData;
echo $decryptedData;
文件上传函数
function uploadFile($file, $targetDirectory) {
$targetFile = $targetDirectory . '/' . basename($file['name']);
move_uploaded_file($file['tmp_name'], $targetFile);
return $targetFile;
}
$uploadedFile = $_FILES['file'];
$targetDirectory = '/path/to/upload/directory';
$uploadedFilePath = uploadFile($uploadedFile, $targetDirectory);
echo "文件已上传至:$uploadedFilePath";