整理自實戰項目,涵蓋字符串、驗證、文件、網絡、圖片、壓縮、SEO 等高頻場景,代碼經測試可直接集成。建議按需複製,注意 PHP 版本兼容性 (部分函數如 eregi 已棄用,請改用 preg_match)。
function readable_random_string($length = 6) {
$conso = ['b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z'];
$vocal = ['a','e','i','o','u'];
$password = '';
for ($i = 1; $i <= $length/2; $i++) {
$password .= $conso[array_rand($conso)] . $vocal[array_rand($vocal)];
}
return $password;
}
function generate_rand($l) {
$c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$rand = '';
for ($i = 0; $i < $l; $i++) {
$rand .= $c[random_int(0, strlen($c)-1)]; // PHP 7+ 用 random_int
}
return $rand;
}
function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs='class="emailencoder"') {
$email = str_replace(['@','.'], ['@','.'], $email);
$linkText = str_replace(['@','.'], ['@','.'], $linkText);
$parts = ['<a href="ma', 'ilto:', '" '.$attrs.' >', '</a>'];
$encoded = '<script type="text/javascript">';
$encoded .= "document.write('$parts[0]');document.write('$parts[1]');";
foreach (str_split($email, 5) as $e) $encoded .= "document.write('$e');";
$encoded .= "document.write('$parts[2]');";
foreach (str_split($linkText, 5) as $l) $encoded .= "document.write('$l');";
$encoded .= "document.write('$parts[3]');</script>";
return $encoded;
}
function is_valid_email($email, $test_mx = false) {
if (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i', $email)) return false;
if ($test_mx) {
list(, $domain) = explode('@', $email);
return checkdnsrr($domain, 'MX'); // PHP 5.3+ 支援 Windows
}
return true;
}
function list_files($dir) {
if (is_dir($dir) && $handle = opendir($dir)) {
while (($file = readdir($handle)) !== false) {
if (!in_array($file, ['.','..','Thumbs.db'])) {
echo "<a target='_blank' href='$dir$file'>$file</a><br>\n";
}
}
closedir($handle);
}
}
function destroyDir($dir, $virtual = false) {
$ds = DIRECTORY_SEPARATOR;
$dir = $virtual ? realpath($dir) : $dir;
$dir = rtrim($dir, $ds);
if (is_dir($dir) && $handle = opendir($dir)) {
while ($file = readdir($handle)) {
if (in_array($file, ['.','..'])) continue;
$path = $dir . $ds . $file;
is_dir($path) ? destroyDir($path) : unlink($path);
}
closedir($handle);
return rmdir($dir);
}
return false;
}
$json = '{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]}';
$obj = json_decode($json);
echo $obj->name; // foo
echo $obj->interest[1]; // php
$xml = simplexml_load_string($xmlString);
foreach ($xml->user as $user) {
echo $user['id'] . ' ' . $user->name . ' ' . $user->email . '<br/>';
}
function create_slug($string) {
return preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
}
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
return $_SERVER['REMOTE_ADDR'];
}
function force_download($file) {
if (isset($file) && file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
function getCloud($data = [], $minFontSize = 12, $maxFontSize = 30) {
$min = min($data); $max = max($data);
$spread = $max - $min ?: 1;
$tags = [];
foreach ($data as $tag => $count) {
$size = $minFontSize + ($count - $min) * ($maxFontSize - $minFontSize) / $spread;
$tags[] = '<a style="font-size: '.floor($size).'px" href="#" title="'.$tag.' count: '.$count.'">'.htmlspecialchars($tag).'</a>';
}
return join("\n", $tags);
}
similar_text($str1, $str2, $percent);
echo $percent; // 相似百分比
function show_gravatar($email, $size=80, $default='', $rating='G') {
echo '<img src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$size.'&d='.urlencode($default).'&r='.$rating.'" width="'.$size.'" height="'.$size.'" />';
}
function myTruncate($string, $limit, $break=' ', $pad='...') {
if (strlen($string) <= $limit) return $string;
if (false !== ($bp = strpos($string, $break, $limit))) {
if ($bp < strlen($string)-1) $string = substr($string, 0, $bp) . $pad;
}
return $string;
}
function create_zip($files = [], $dest = '', $overwrite = false) {
if (file_exists($dest) && !$overwrite) return false;
$zip = new ZipArchive();
if ($zip->open($dest, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) return false;
foreach ($files as $file) if (file_exists($file)) $zip->addFile($file, basename($file));
$zip->close();
return file_exists($dest);
}
function unzip_file($file, $dest) {
$zip = new ZipArchive();
if ($zip->open($file) !== true) die('Could not open archive');
$zip->extractTo($dest);
$zip->close();
}
if (!preg_match('/^(https?|ftp):/i', $_POST['url'])) $_POST['url'] = 'https://'.$_POST['url'];
function makeClickableLinks($text) {
$text = preg_replace('/\b((https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', '<a href="$1">$1</a>', $text);
$text = preg_replace('/\b(www\.[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', '<a href="https://$1">$1</a>', $text);
$text = preg_replace('/\b([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,})\b/i', '<a href="mailto:$1">$1</a>', $text);
return $text;
}
function resize_image($filename, $tmpname, $xmax, $ymax) {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$im = match($ext) {
'jpg','jpeg' => imagecreatefromjpeg($tmpname),
'png' => imagecreatefrompng($tmpname),
'gif' => imagecreatefromgif($tmpname),
default => false
};
if (!$im) return false;
$x = imagesx($im); $y = imagesy($im);
if ($x <= $xmax && $y <= $ymax) return $im;
if ($x >= $y) { $newx = $xmax; $newy = $newx * $y / $x; }
else { $newy = $ymax; $newx = $x / $y * $newy; }
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresampled($im2, $im, 0,0,0,0, $newx, $newy, $x, $y); // 高質量
return $im2;
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
// AJAX 請求
}
現代化提示:原文使用 eregi、split、rand 等已棄用函數,上述代碼已替換為 preg_match、explode、random_int/array_rand、imagecopyresampled 等現代替代品。實際使用請根據 PHP 版本調整。