substr_replace(string, replacement, start, length) 將字串從 start 位置、長度 length 的部分替換為 replacement。注意:中文字串需先處理編碼,否則會產生亂碼。
$string1 = "123456789";
echo substr_replace($string1, '###', 0); // ###
echo substr_replace($string1, '###', 5); // 12345###
echo substr_replace($string1, '###', 0, 0); // ###123456789
echo substr_replace($string1, '###', 8, -2); // 12345678###9
echo substr_replace($string1, '###', -6, -1); // 123###9
echo substr_replace($string1, '###', -1); // 123###9
echo substr_replace($string1, '###', 1, -1); // 1###9
echo substr_replace($string1, '###', 1, 1); // 1###3456789
$var = 'ABCDEFGH:/MNRPQR/';
echo substr_replace($var, 'bob', 0); // bob
echo substr_replace($var, 'bob', 0, strlen($var)); // bob
echo substr_replace($var, 'bob', 0, 0); // bobABCDEFGH:/MNRPQR/
echo substr_replace($var, 'bob', 10, -1); // ABCDEFGH:/bob/
echo substr_replace($var, 'bob', -7, -1); // ABCDEFGH:/bob/
echo substr_replace($var, '', 10, -1); // ABCDEFGH:// (刪除)
$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '...';
$maxlength = 25 - strlen($separator);
$start = $maxlength / 2;
$trunc = strlen($longString) - $maxlength;
echo substr_replace($longString, $separator, $start, $trunc);
// 輸出:abcdefghijk...456789z.jpg
function truncate($text, $numb) {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text, 0, strrpos($text, " "));
if (substr($text, -1) == ".") {
$text = substr($text, 0, strrpos($text, "."));
}
$text .= "...";
}
return htmlentities($text, ENT_QUOTES);
}
$text = 'welcome to nowamagic, welcome to nowamagic, welcome to nowamagic';
echo truncate($text, 35);
// 輸出:welcome to nowamagic, welcome...
mb_substr_replace 或先轉 UTF-8 陣列處理。start 為負數時從字串末尾倒數;length 為負數表示保留尾部字元數。length = 0 視為插入模式(不刪除原字元)。