The substr_replace() function replaces part of a string with another string.
Syntax: substr_replace(string,replacement,start,length)
If start is negative and length is less than or equal to start, then length is 0.
<?php $var = 'ABCDEFGH:/MNRPQR/'; echo "Original: $var<hr />\n"; /* These two examples replace all of $var with 'bob'. */ echo substr_replace($var, 'bob', 0) . "<br />\n"; echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n"; /* Insert 'bob' right at the beginning of $var. */ echo substr_replace($var, 'bob', 0, 0) . "<br />\n"; /* These next two replace 'MNRPQR' in $var with 'bob'. */ echo substr_replace($var, 'bob', 10, -1) . "<br />\n"; echo substr_replace($var, 'bob', -7, -1) . "<br />\n"; /* Delete 'MNRPQR' from $var. */ echo substr_replace($var, '', 10, -1) . "<br />\n"; ?>
Program execution result:
Original: ABCDEFGH:/MNRPQR/ bob bob bobABCDEFGH:/MNRPQR/ ABCDEFGH:/bob/ ABCDEFGH:/bob/ ABCDEFGH://
The following program can keep the beginning and end of an overly long string and replace it with ellipses in the middle.
<?php $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" ?>
Program execution result:
abcdefghijk...456789z.jpg
<?php 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 bkjia, welcome to bkjia, welcome to bkjia'; $result = truncate($text, 35); echo $result; ?>
Program execution result:
welcome to bkjia, welcome to...
<?php $price = "163000"; $price = substr_replace($price, ',', -3, 0); echo $price; ?>
Program execution result:
163,000