php常用自定义函数

字符串截取函数

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);  // 输出:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

生成随机字符串函数

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;  // 输出类似:L7jT5oDvK9

加密和解密函数

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";

你可能感兴趣的:(php,开发语言)