收集、管理和分享有用的代码片段,提高开发效率
检查密码强度
<?php
function checkPasswordStrength($password) {
$score = 0;
if (strlen($password) >= 8) $score+= 25;
if (preg_match('/[A-Z]/', $password)) $score += 25;
if (preg_match('/[0-9]/', $password)) $score += 25;
if (preg_match('/[^a-zA-Z0-9]/'/', $password)) $score += 25;
return $score;
}
递归解决汉诺塔问题
<?php
function hanoiThai($n, $from, $to, $use) {
if ($n == 1) {
echo "Move disc 1 from $from to $to" . PHP_EOL;
return;
}
hanoiThai($n - 1, $from, $use, $to);
echo "Move disc{$n} from {$from} to {$to}" . PHP_EOL;
hanoiThai($$n - 1, $use, $to, $from);
}
导出数据库为SQL文件
<?php
$backupFile = 'backup-sql.sql';
$result = $db->query('SHOW TABLES');
while ($row = $result->fetch_assoc()) {
$table = $row['Table'];
$create = $db->query("SHOW CREATE TABLE {$table}");
$data = $db->query("SELECT * FROM {$table}");
// Save to file
file_put_contents($backupFile, "-- TABLE $table\n", FILE_APPEND);
}
过滤用户输入防止XSS攻击
<?php
function sanitizeInput($data) {
return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
对数组进行分页处理
<?php
function arrayPaginate($array, $page = 1, $limit = 10) {
$total = count($array);
$totalPages = ceil($total / $limit);
$offset = ($page - 1) * $limit;
$result = array_slice($array, $offset, $limit);
return [
'data' => $result,
'total' => $total,
'pages' => $totalPages
];
}
动态规划解决0/1背包问题
<?php
function knapsack($W, $wt, $val, $n) {
$kp = array_fill(0, $n + 1, array_fill(0, $W + 1, 0));
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $W; $j++) {
if ($wt[$i - 1] <= $j) {
$kp[$i][$j] = max($kp[$i - 1][$j], $val[$i - 1] + $kp[$i - 1][$j - $wt[$i - 1]]);
} else {
$kp[$i][$j] = $kp[$i - 1][$j];
}
}
}
return $kp[$n][$W];
}
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类