The Substr_replace () function replaces part of a string with another string.
Usage
Substr_replace (String,replacement,start,length)
Note When the string contains Chinese, garbled characters will appear without special handling.
| The code is as follows |
Copy Code |
|
<?php
$string 1 = "123456789";
Echo Substr_replace ($string 1, ' ### ', 0);
//###
Echo Substr_replace ($string 1, ' ### ', 5);
12345###
Echo Substr_replace ($string 1, ' ### ', 0,0);
# # #123456789
Echo Substr_replace ($string 1, ' ### ', 8,-2);
12345678## #9
Echo Substr_replace ($string 1, ' ### ', -6,-1);
123## #9
echo "n";
Echo Substr_replace ($string 1, ' ### ',-1);
123## #9
echo "n";
Echo Substr_replace ($string 1, ' ### ', 1,-1);
1## #9
Echo Substr_replace ($string 1, ' ### ', 1, 1);
1## #3456789
?> |
Example 2
| The code is as follows |
Copy Code |
<?php
$var = ' abcdefgh:/mnrpqr/';
echo "Original: $var /* Two examples replace all of the $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 ' into $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";
? |
original:abcdefgh:/mnrpqr/
Bob
Bob
bobabcdefgh:/mnrpqr/
abcdefgh:/bob/
abcdefgh:/bob/
abcdefgh://
Replaces part of an excessive string with an ellipsis
The following program can keep the long string at the end and the middle with an ellipsis instead.
| The code is as follows |
Copy Code |
<?php
$longString = ' abcdefghijklmnopqrstuvwxyz0123456789z.jpg ';
$separator = ' ... ';
$separatorlength = strlen ($separator);
String that needs to be preserved
$maxlength = 25-$separatorlength;
Starting from half the length
$start = $maxlength/2;
Calculate offset
$trunc = strlen ($longString)-$maxlength;
Echo Substr_replace ($longString, $separator, $start, $trunc);
Prints "Abcdefghij ... 56789z.jpg "
?> |
Program Run Result:
Abcdefghijk ... 456789z.jpg
Program List: Replace the extra characters with ellipses
| The code is as follows |
Copy Code |
|
<?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 Nowamagic, Welcome to Nowamagic, welcome to Nowamagic ';
$result = t Runcate ($text, 35);
Echo $result;
? |
Well, you probably know how this function works.