1. 移除 HTML 標簽
$text = strip_tags($input, '<p><br>'); // 保留允許的標簽
2. 獲取兩個標記之間的內容
function getBetween($content, $start, $end) {
$r = explode($start, $content, 2);
if (isset($r[1])) {
$r = explode($end, $r[1], 2);
return $r[0];
}
return '';
}
3. 將文本中的 URL 自動轉為可點擊鏈接
$url = 'Jean-Baptiste Jung (https://www.jb51.net)';
$url = preg_replace('#https?://([^\s\'"]+)#', '<a href="$0" target="_blank">$0</a>', $url);
4. 將長文本按單詞拆分為指定長度塊(如 140 字符)
function splitToChunks($to, $text, $maxLen = 140) {
$limit = $maxLen - strlen($to);
$words = explode(' ', $text);
$chunks = [''];
$i = 0;
foreach ($words as $word) {
if (strlen($chunks[$i] . ' ' . $word) <= $limit) {
$chunks[$i] .= ($chunks[$i] ? ' ' : '') . $word;
} else {
$chunks[++$i] = $word;
}
}
return $chunks;
}
5. 刪除字符串中的所有 URL
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
6. 生成 SEO 友好的 URL Slug
function slug($str) {
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', '-', $str);
return trim($str, '-');
}
7. 解析 CSV 文件
$fh = fopen("contacts.csv", "r");
while ($line = fgetcsv($fh, 1000, ",")) {
echo "Contact: {$line[1]}";
}
fclose($fh);
8. 大小寫不敏感字符串搜索
function contains($needle, $haystack, $ignoreCase = true) {
if ($ignoreCase) {
$needle = strtolower($needle);
$haystack = strtolower($haystack);
}
return strpos($haystack, $needle) !== false;
}
9. 判斷字符串是否以某子串開頭
function startsWith($needle, $haystack) {
return strncmp($haystack, $needle, strlen($needle)) === 0;
// PHP 8+ 可直接用 $haystack->startsWith($needle)
}
10. 從文本中提取所有 Email 地址
function extractEmails($str) {
$regex = '/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i';
preg_match_all($regex, $str, $matches);
return $matches[0] ?? [];
}
$test = 'Contact: test@example.org, support@site.com';
print_r(extractEmails($test));
// Array ( [0] => test@example.org [1] => support@site.com )
使用建議
- 正則表達式雖強大,但對於簡單操作(如去標簽、大小寫轉換)優先使用內建函數(
strip_tags, strtolower 等),性能更好且可讀性更高。
- 處理用戶輸入時,務必結合
htmlspecialchars() 防止 XSS。
- CSV 解析建議使用
fgetcsv() 自動處理引號、換行等邊界情況。