substr_replace與str_replace有一點像就是直接把字串替換一部份了,下面小編來給各位同學介紹一下操作方法。
substr_replace() 函數把字串的一部分替換為另一個字串。
用法
substr_replace(string,replacement,start,length)
注意當字串包含中文時,不經過特殊處理會出現亂碼。
| 代碼如下 |
複製代碼 |
$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 "n"; echo substr_replace($string1,'###',-1); //123###9 echo "n"; echo substr_replace($string1,'###',1,-1); //1###9 echo substr_replace($string1,'###',1,1); //1###3456789 ?> |
例2
| 代碼如下 |
複製代碼 |
$var = 'ABCDEFGH:/MNRPQR/'; echo "Original: $varn"; /* 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/
bob
bob
bobABCDEFGH:/MNRPQR/
ABCDEFGH:/bob/
ABCDEFGH:/bob/
ABCDEFGH://
將過長的字串用省略符號代替一部分
下面的程式可以將過長的字串保留首尾,中間用省略符號代替。
| 代碼如下 |
複製代碼 |
$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg'; $separator = '...'; $separatorlength = strlen($separator) ; // 需要保留的字串 $maxlength = 25 - $separatorlength; // 從一半的長度開始 $start = $maxlength / 2 ; // 計算位移量 $trunc = strlen($longString) - $maxlength; echo substr_replace($longString, $separator, $start, $trunc); //prints "abcdefghij...56789z.jpg" ?> |
程式運行結果:
abcdefghijk...456789z.jpg
Program List:將多出的字元用省略符號代替
| 代碼如下 |
複製代碼 |
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," ")); //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 nowamagic, welcome to nowamagic, welcome to nowamagic'; $result = truncate($text, 35); echo $result; ?> |
好了你大概會知道此函數的作用了。
http://www.bkjia.com/PHPjc/632654.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/632654.htmlTechArticlesubstr_replace與str_replace有一點像就是直接把字串替換一部份了,下面小編來給各位同學介紹一下操作方法。 substr_replace() 函數把字串的一...