substr_replace()函數介紹
substr_replace() 函數把字串的一部分替換為另一個字串。
文法:substr_replace(string,replacement,start,length)
- 參數string,必需。規定要檢查的字串。
- 參數replacement,必需。規定要插入的字串。
- 參數start,必需。規定在字串的何處開始替換。正數 - 在第 start 個位移量開始替換;負數 - 在從字串結尾的第 start 個位移量開始替換;0 - 在字串中的第一個字元處開始替換。
- 參數charlist,可選。規定要替換多少個字元。正數 - 被替換的字串長度;負數 - 從字串末端開始的被替換字元數;0 - 插入而非替換。
如果 start 是負數且 length 小於等於 start,則 length 為 0。
Program List:substr_replace()函數基本用法
\n";/* These two examples replace all of $var with 'bob'. */echo substr_replace($var, 'bob', 0) . "
\n";echo substr_replace($var, 'bob', 0, strlen($var)) . "
\n";/* Insert 'bob' right at the beginning of $var. */echo substr_replace($var, 'bob', 0, 0) . "
\n";/* These next two replace 'MNRPQR' in $var with 'bob'. */echo substr_replace($var, 'bob', 10, -1) . "
\n";echo substr_replace($var, 'bob', -7, -1) . "
\n";/* Delete 'MNRPQR' from $var. */echo substr_replace($var, '', 10, -1) . "
\n";?>
程式運行結果:
Original: ABCDEFGH:/MNRPQR/bobbobbobABCDEFGH:/MNRPQR/ABCDEFGH:/bob/ABCDEFGH:/bob/ABCDEFGH://
Program List:將過長的字串用省略符號代替一部分
下面的程式可以將過長的字串保留首尾,中間用省略符號代替。
程式運行結果:
abcdefghijk...456789z.jpg
Program List:將多出的字元用省略符號代替
$numb) {$text = substr($text, 0, $numb);$text = substr($text,0,strrpos($text," ")); //This strips the full stop: if ((substr($text, -1)) == ".") { $text = substr($text,0,(strrpos($text,"."))); }$etc = "..."; $text = $text.$etc;} $text = htmlentities($text, ENT_QUOTES); return $text;}//Call function$text = 'welcome to bkjia, welcome to bkjia, welcome to bkjia';$result = truncate($text, 35);echo $result;?>
程式運行結果:
welcome to bkjia, welcome to...
Program List:給金錢數額加上逗號
程式運行結果:
163,000
http://www.bkjia.com/PHPjc/752379.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752379.htmlTechArticlesubstr_replace()函數介紹 substr_replace() 函數把字串的一部分替換為另一個字串。 文法:substr_replace(string,replacement,start,length) 參數string,必...