1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| <?php class StringUtils { public static function generateRandomString($length = 10, $characters = null) { if ($characters === null) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; } $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } public static function camelToSnake($string) { return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $string)); } public static function snakeToCamel($string, $capitalizeFirst = false) { $result = str_replace('_', '', ucwords($string, '_')); return $capitalizeFirst ? $result : lcfirst($result); } public static function startsWith($haystack, $needle) { return substr($haystack, 0, strlen($needle)) === $needle; } public static function endsWith($haystack, $needle) { return substr($haystack, -strlen($needle)) === $needle; } public static function safeCompare($a, $b) { if (function_exists('hash_equals')) { return hash_equals($a, $b); } if (strlen($a) !== strlen($b)) { return false; } $result = 0; for ($i = 0; $i < strlen($a); $i++) { $result |= ord($a[$i]) ^ ord($b[$i]); } return $result === 0; } public static function smartTruncate($string, $length, $suffix = '...') { if (mb_strlen($string, 'UTF-8') <= $length) { return $string; } $truncated = mb_substr($string, 0, $length, 'UTF-8'); $lastSpace = mb_strrpos($truncated, ' ', 0, 'UTF-8'); if ($lastSpace !== false && $lastSpace > $length * 0.7) { $truncated = mb_substr($truncated, 0, $lastSpace, 'UTF-8'); } return $truncated . $suffix; } public static function highlightKeywords($text, $keywords, $highlightClass = 'highlight') { if (!is_array($keywords)) { $keywords = [$keywords]; } foreach ($keywords as $keyword) { $text = preg_replace( '/(' . preg_quote($keyword, '/') . ')/i', '<span class="' . $highlightClass . '">$1</span>', $text ); } return $text; } }
echo "随机字符串:" . StringUtils::generateRandomString(12) . "\n"; echo "驼峰转下划线:" . StringUtils::camelToSnake('getUserName') . "\n"; echo "下划线转驼峰:" . StringUtils::snakeToCamel('user_name') . "\n"; echo "以Hello开头:" . (StringUtils::startsWith('Hello World', 'Hello') ? '是' : '否') . "\n"; echo "以World结尾:" . (StringUtils::endsWith('Hello World', 'World') ? '是' : '否') . "\n";
$longText = "这是一个很长的文本内容,需要进行智能截取处理,确保不会截断单词"; echo "智能截取:" . StringUtils::smartTruncate($longText, 20) . "\n";
$content = "PHP是一种流行的编程语言,PHP开发很有趣"; echo "高亮关键词:" . StringUtils::highlightKeywords($content, ['PHP', '编程']) . "\n"; ?>
|