1. 區間字串截取(支援多位元組)
<?php
/**
* 取得 $begin 與 $end 之間的字串
* @param string $begin 起始標記
* @param string $end 結束標記
* @param string $str 來源字串
* @return string|null 找不到回傳 null
*/
function get_between(string $begin, string $end, string $str): ?string
{
$startPos = mb_strpos($str, $begin);
if ($startPos === false) return null;
$startPos += mb_strlen($begin);
$endPos = mb_strpos($str, $end, $startPos);
if ($endPos === false) return null;
return mb_substr($str, $startPos, $endPos - $startPos);
}
// 用法
$html = '<div>目標內容</div>';
echo get_between('<div>', '</div>', $html); // '目標內容'
?>
2. cURL GET 封裝(自動追蹤重導向、回傳 Header+Body)
<?php
function curl_get(string $url, array $options = []): string
{
$ch = curl_init($url);
curl_setopt_array($ch, array_merge([
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true, // 含回應標頭
CURLOPT_FOLLOWLOCATION => true, // 自動追蹤 301/302
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false, // 開發環境可關閉驗證
], $options));
$response = curl_exec($ch);
if ($response === false) {
throw new RuntimeException('cURL error: ' . curl_error($ch));
}
curl_close($ch);
return $response;
}
// 用法
$resp = curl_get('https://api.example.com/users');
list($header, $body) = explode("\r\n\r\n", $response, 2);
3. 陣列轉巢狀樹(分類、留言板、選單)
<?php
/**
* 扁平陣列轉巢狀樹
* @param array $items 扁平資料 [['id'=>1,'pid'=>0,'name'=>'A'], ...]
* @param string $idKey 主鍵欄位名
* @param string $parentKey 父鍵欄位名
* @param string $childKey 子節點鍵名
* @return array 巢狀結構
*/
function build_tree(array $items, string $idKey = 'id', string $parentKey = 'pid', string $childKey = 'children'): array
{
$map = [];
foreach ($items as $item) {
$map[$item[$idKey]] = $item;
}
$tree = [];
foreach ($items as $item) {
$pid = $item[$parentKey];
if (isset($map[$pid])) {
$map[$pid][$childKey][] = &$map[$item[$idKey]];
} else {
$tree[] = &$map[$item[$idKey]];
}
}
unset($map);
return $tree;
}
// 測試
$data = [
['id'=>1, 'pid'=>0, 'name'=>'根節點'],
['id'=>2, 'pid'=>1, 'name'=>'子節點A'],
['id'=>3, 'pid'=>1, 'name'=>'子節點B'],
['id'=>4, 'pid'=>2, 'name'=>'孫節點'],
];
print_r(build_tree($data));
/*
Array
(
[0] => Array
(
[id] => 1
[pid] => 0
[name] => 根節點
[children] => Array
(
[0] => Array ( [id]=>2 ... [children]=>Array([0]=>孫節點) )
[1] => Array ( [id]=>3 ... )
)
)
)
*/
?>
使用提醒
- 字串截取前若為 HTML,先用
strip_tags() 或 html_entity_decode() 處理。
- cURL 封裝建議加入重試機制(Guzzle 內建支援)。
- 樹狀結構遞迴深度過大(>1000)可能導致堆疊溢位,需改用迭代或遞迴限制。