(PHP 4, PHP 5)
substr_replace — 替换字符串的子串
substr_replace() 在字符串 string
的副本中将由 start
和可选的 length
参数限定的子字符串使用 replacement
进行替换。
string
输入字符串。
An array of strings can be provided, in which
case the replacements will occur on each string in turn. In this case,
the replacement
, start
and length
parameters may be provided either as
scalar values to be applied to each input string in turn, or as
arrays, in which case the corresponding array element will
be used for each input string.
replacement
替换字符串。
start
如果 start
为正数,替换将从 string
的 start
位置开始。
如果 start
为负数,替换将从 string
的倒数第 start
个位置开始。
length
如果设定了这个参数并且为正数,表示 string
中被替换的子字符串的长度。如果设定为负数,它表示待替换的子字符串结尾处距离 string
末端的字符个数。如果没有提供此参数,那么它默认为 strlen( string
) (字符串的长度)。当然,如果 length
为 0,那么这个函数的功能为将 replacement
插入到 string
的 start
位置处。
返回结果字符串。如果 string
是个数组,那么也将返回一个数组。
Example #1 substr_replace() 范例
<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";
/* 这两个例子使用 “bob” 替换整个 $var。*/
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";
/* 将 “bob” 插入到 $var 的开头处。*/
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";
/* 下面两个例子使用 “bob” 替换 $var 中的 “MNRPQR”。*/
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";
/* 从 $var 中删除 “MNRPQR”。*/
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>
Example #2 Using substr_replace() to replace multiple strings at once
<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');
// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";
// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";
// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>
以上例程会输出:
A: YYY; B: YYY; C: YYY A: AAA; B: BBB; C: CCC A: AAAXX; B: BBBX; C: CCC
Note: 此函数可安全用于二进制对象。
blessador at gmail dot com (2013-06-18 08:36:58)
<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>
ensure to remove the double quot " at the end of substr_replace ($price, ',', -3, 0)" in the above code to avoid error.
tuppisau at gmail dot com at example dot com (2012-02-23 18:54:18)
If anyone is in need, here is a simple function to chop string without chopping the word and leaving the sentence incomplete. This function chops the desired length of string and after that finds the last white space in the chopped string. After that it again chops the string to the position where the last white space was found and replace it with our desired filler:
<?php
function str_replacer($_string, $_length, $_replacer = ' ...'){
// Remove any HTML tags present in the string
$_string = strip_tags($_string);
if(strlen($_string) > $_length){
// Find the position for last white space after the string has been shortened to our desired length
// This helps us to shorten the string without chopping the character or word from the middle
// ASCII value for the white space is 32
$_last_white_space_pos = strripos(substr($_string, 0, $_length), 32);
return substr_replace($_string, $_replacer, $_last_white_space_pos);
}
else{
return $_string;
}
}
?>
// How to call
<?php echo str_replacer('My name is John, what is yours?', 25) ?>
This will result in:
My name is John, what is ...
elloromtz at gmail dot com (2010-04-17 23:23:55)
It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0.
<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?>
Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>
<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?>
Same as:
<?php
substr_replace('huevos','x',-2,0); //huevxos
?>
Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it)
<?php
substr_replace('abcd', 'x', 0, -4); //xabcd
?>
Same as:
<?php
substr_replace('abcd','x',0,0); //xabcd
?>
<?php
substr_replace('abcd', 'x', 1, -3); //axbcd
?>
Same as:
<?php
substr_replace('abcd', 'x', 1, 0); //axbcd
?>
den dot gierling at web dot de (2010-02-19 10:32:58)
My problem was that substr_replace() always added $replacement, so i wrote my own function.
This function only adds $replacement, if substr() took action.
The parameter $length is optional - like substr()'s.
Or I was too stupid using $start and $length...
<?php
function substr_replace_provided($string,$replacement,$start,$length=NULL)
{
$tmp=substr($string,$start,$length);
if($string!==$tmp) {
$string = $tmp.$replacement;
}
return $string;
}
?>
kalim dot fleet at gmail dot com (2009-10-10 09:49:19)
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly 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"
?>
admiral at nuclearpixel dot com (2009-10-06 11:54:47)
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their own string truncation functions, but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.
Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.
I hope this can help someone out!
-Admiral Potato
<?php
function admiralsTruncate($string, $length){
settype($string, 'string');
settype($length, 'integer');
for($a = 0; $a < $length AND $a < strlen($string); $a++){
$output .= $string[$a];
}
return($output);
}
$my_string = 'cfcd208495d565ef66e7dff9f98764da';
echo admiralsTruncate($my_string, 6); // outputs: cfcd20
echo '<br>';
echo admiralsTruncate($my_string, 9); // outputs: cfcd20849
?>
gcdreak at farfaraway dot com (2009-04-14 07:56:11)
This is a good method to check file chmod value:
<?php
$file = "../files/sample.txt";
$rights = decoct(fileperms($file));
echo "File rights: ".substr_replace($rights, "", 0, 3);
?>
billg AT microsoft.com (2009-04-07 19:31:30)
Forget all of the mb_substr_replace() implementations mentioned in this page, they're all buggy.
Here is a version that mimics the behavior of substr_replace() exactly:
<?php
if (function_exists('mb_substr_replace') === false)
{
function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
{
if (extension_loaded('mbstring') === true)
{
$string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);
if ($start < 0)
{
$start = max(0, $string_length + $start);
}
else if ($start > $string_length)
{
$start = $string_length;
}
if ($length < 0)
{
$length = max(0, $string_length - $start + $length);
}
else if ((is_null($length) === true) || ($length > $string_length))
{
$length = $string_length;
}
if (($start + $length) > $string_length)
{
$length = $string_length - $start;
}
if (is_null($encoding) === true)
{
return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
}
return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
}
return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
}
}
?>
juichenieder-phnet at yahoo dot co dot uk (2009-03-25 10:58:56)
I've just taken a look at the post by ntoniazzi and I have a very small correction to make.
In the second if statement, it should be a triple equals, so:
<?php if ($length === null) ?>
It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short. I hope this helps someone.
NiX0n at fragfest dot cx (2008-10-09 09:41:05)
The preemptive test to see if $string is "too long" shouldn't add strlen($replacement) to $max. $max should represent the absolute maximum length of string returned. The size of the $replacement is irrelevant in that determination.
The rest of the function (unchanged below) operates as defined above. Meaning, the size of the $replacement is subtracted from the $max, so that the returned string is exactly the length of $max.
<?php
function truncate($string, $max = 20, $replacement = '')
{
if (strlen($string) <= $max)
{
return $string;
}
$leave = $max - strlen ($replacement);
return substr_replace($string, $replacement, $leave);
}
?>
spcl dot delivery at gmail dot com (2008-07-27 16:14:58)
the version of my predecessor will add $rep even if the string is shorter than max. fixed version:
<?php
function truncate($string, $max = 20, $rep = '')
{
if (strlen($string) <= ($max + strlen($rep)))
{
return $string;
}
$leave = $max - strlen ($rep);
return substr_replace($string, $rep, $leave);
}
?>
To preserve the filename extension you can call it like this:
truncate([filename], 30, '...' . end(explode('.', [filename])))
eblejr AT phrebh DOT com (2008-06-04 08:42:22)
PHP version of Java's removeCharAt() function:
<?php
function removeCharAt($str, $int){
return substr_replace($str,"",$int,1);
}
?>
William Barry (2008-04-23 12:18:44)
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved. I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.
This was my alternative solution, and it seems to work well:
<?php
function stripNestedLists($str)
{
$str2 = $str;
$lastStr = $str2;
do
{
// Find the first closing ul
$cul = strpos($str2, '</ul>');
$ul = 0;
$lastUL = 0;
do
{
// Find the next opening ul
$lastUL = $ul;
$ul = strpos($str2, '<ul', $ul+1);
}
while ($ul !== false && $ul < $cul);
$lastStr = $str2;
$str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
$str2 = trim($str2);
}
while (strlen($str2) > 0);
return $lastStr;
}
?>
Hope this helps someone.
jaimthorn at yahoo dot com (2008-03-25 22:53:22)
I recently needed a routine that would remove the characters in one string from another, like the regex
<?php
$result = preg_replace("/[$chars]/", "", $string);
?>
and I needed it to be fast, and accept pretty much all input. The regex above won't work when strlen($chars) == 0. I came up with this, admittedly pretty horrible-looking code, that is quite fast:
<?php
function RemoveChars($string, $chars)
{
return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars, str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}
?>
According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer strings, my routine is faster. What does it do? Let's say you want to remove the period, the comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't this...") that also occur in the input (".,!") to the characters in the same position in the output ("..."). In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will fail. If it's empty, then the unprocessed string is returned.
ntoniazzi at sqli dot com (2008-02-14 01:07:29)
Almost... In the previous note, change this :
<?php
function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
if ($encoding == null) $encoding = mb_internal_encoding();
if($start < 0) $start = mb_strlen($string) + $start;
[...]
?>
ntoniazzi at sqli dot com (2008-02-13 09:58:47)
There is a mistake in the mb_substr_replace function below, when the $length parameter is given negative. Here is a working version.
<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
//Same parameters as substr_replace with the extra encoding parameter.
function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
if ($encoding == null) $encoding = mb_internal_encoding();
if ($length == null) {
return mb_substr($string, 0, $start, $encoding) . $replacement;
}
else {
if($length < 0) $length = mb_strlen($string, $encoding) - $start + $length;
return
mb_substr($string, 0, $start, $encoding) .
$replacement .
mb_substr($string, $start + $length, mb_strlen($string, $encoding), $encoding);
}
}
}
?>
alishahnovin at hotmail dot com (2007-08-07 12:56:01)
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)
The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...
Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.
<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
$punctuation = ".!?:;,-"; //punctuation you want removed
$text = (strspn(strrev($text), $punctuation)!=0)
?
substr($text, 0, -strspn(strrev($text), $punctuation))
:
$text;
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
?>
I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):
<?php
function mtruncate($text, $numb, $etc = " ... ") {
$first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
$second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
return $first_part.$etc.$second_part;
}
?>
joecorcoran at gmail dot com (2007-08-07 06:50:59)
I've made a minor amendment to the function in the post below, to strip away the full stop (period) if the truncation occurs at the exact end of a sentence (the full stop spoils the ellipsis):
<?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
truncate($text, 75);
www.kigoobe.com (2007-03-21 02:00:25)
The two truncate functions provided below, have some major short comings.
1. They may cut a word in half
2. In case you are using htmlentities to get user input or are using wysiwyg editors to get user input, you can get truncated text like "he told C&eac..." instead of "he told Cécile" or "he told".
Here is what I use -
<?php
function truncate($text,$numb) {
// source: www.kigoobe.com, please keep this if you are using the function
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
$etc = " ...";
$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
// Now, to use this function, you can call that as -
truncate($text, 75);
?>
chuayw2000 at hotmail dot com (2005-12-09 03:33:52)
I don't know if this function is multibyte safe but I've written a function that will do the same in multibyte mode.
<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
//Same parameters as substr_replace with the extra encoding parameter.
function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
if ($encoding == null){
if ($length == null){
return mb_substr($string,0,$start).$replacement;
}
else{
return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
}
}
else{
if ($length == null){
return mb_substr($string,0,$start,$encoding).$replacement;
}
else{
return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
}
}
}
}
?>
michael(at)webstaa(dot)com (2005-12-05 20:47:28)
I created this because of the need to mask a credit-card number like **** **** **** 8862
string mask ( string str, int start [, int length] )
mask() masks a copy of str delimited by the start and (optionally) length parameters with asterisks (*) in place of non-whitespace characters
<?php
function mask ( $str, $start = 0, $length = null ) {
$mask = preg_replace ( "/\S/", "*", $str );
if ( is_null ( $length )) {
$mask = substr ( $mask, $start );
$str = substr_replace ( $str, $mask, $start );
} else {
$mask = substr ( $mask, $start, $length );
$str = substr_replace ( $str, $mask, $start, $length );
}
return $str;
}
?>
hermes at andycostell dot com (2005-08-27 11:48:35)
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn't work as written here.
Original:
function add_3dots($string,$repl,$start,$limit) {
if(strlen($string) > $limit) {
return substr_replace(strip_tags($string),$repl,$start,$limit);
} else {
return $string;
};
};
I suggest:
function add_3dots($string,$repl,$limit) {
if(strlen($string) > $limit) {
return substr_replace(strip_tags($string),$repl,$limit-strlen($repl));
} else {
return $string;
}
}
Usage:
$max_length=10;//the max number of characters you want to display
$too_long_string="BLAH BLAH BLAH BLAH BLAH etc.";//the string you want to shorten (if it's longer than the $limit)
$shorter_string=add_3_dots($too_long_string,"...",$max_length);
Guru Evi (2005-07-13 00:44:44)
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.
I wanted to replace the end of the string with ... if the string was too long to display (for instance article preview on a website). The problem was that my string was sometimes not that long and it still added the replacement string. So I wrote a function to replace substr_replace in my website:
function add_3dots($string,$repl,$start,$limit) {
if(strlen($string) > $limit) {
return substr_replace(strip_tags($string),$repl,$start,$limit);
} else {
return $string;
};
};
I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn't)
tekrat at 2d dot com (2005-01-06 08:55:46)
Here's a slightly revised version of the truncation function above.
Theres isn't much of a reason to add in the $rep at the end of the original string is less then the truncation break point.
<?php
function truncate($substring, $max = 50, $rep = '...') {
if(strlen($substring) >= 1){
$string = $substring;
}
$leave = $max - strlen ($rep);
if(strlen($string) > $max){
return substr_replace($string, $rep, $leave);
}else{
return $string;
}
}
?>
[EDIT BY danbrown AT php DOT net: Contains a bugfix by (ogt AT parasane DOT com) (which was me ;-P) from 21-JAN-05 at 11:02 EST.]
danieldoorduin at hotmail dot com (2004-12-10 02:48:40)
Using substr_replace() can be avoided by using substr() instead:
<?
$string = substr($string, 0, $position_needle).$replace.substr($string, $position_needle+$length_needle);
?>
This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn't a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
titbits at nospam-4logical dot co dot uk (2004-08-04 14:28:44)
A simple but useful 'pluralize' function using substr_replace:
function pluralize($noun) {
if ($noun{strlen($noun) -1} == "y")
$noun = substr_replace($noun, "ies", strlen($noun) -1);
else
$noun .= "s";
return $noun;
}
Handy when displaying dynamic text.
dmron (2004-06-17 16:34:10)
Regarding "...", even the short functions are too long and complicated, and there's no need to use substr_replace. substr() works better and is way faster prior to 4.3.5 as the below poster stated.
function shorten( $str, $num = 100 ) {
if( strlen( $str ) > $num ) $str = substr( $str, 0, $num ) . "...";
return $str;
}
philip (2004-05-13 12:55:38)
The substr_replace() function is extremely slow in PHP versions prior to 4.3.5 and 5.0.0 so consider using an alternative before this time.
tony at outshine dot com (2004-05-10 02:25:00)
The comment by geniusdex is a good one. Short, simple functions are the best. But if the string is not longer than the limit set, NOTHING is returned. Here is the function re-done to always return a string:
<?php
function dot($str, $len, $dots = "...") {
if (strlen($str) > $len) {
$dotlen = strlen($dots);
$str = substr_replace($str, $dots, $len - $dotlen);
}
return $str;
}
?>
geniusdex ( at ) brz ( dot ) nu (2004-02-23 07:33:16)
This is my version of making dotted strings:
<?php
function dot($str, $len, $dots = "...") {
if (strlen($str) > $len) {
$dotlen = strlen($dots);
substr_replace($str, $dots, $len - $dotlen);
}
}
?>
Thijs Wijnmaalen (thijs[at]nllinux.nl) (2004-01-20 11:05:45)
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.
<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {
$theReturn = $text;
$lastSpace = false;
if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);
if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');
if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}
if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>
neon at lordneon dot com (2003-11-05 04:40:53)
The easiest way (I think) to add trailing dots after a string which in my case are too long is:
<?
function dots($num, $string) {
if (strlen($string) < $num) {
$string = substr_replace($string, '...', '-10', $num);
}
return $string;
}
Then on your page do something like:
<? echo dots("30" $row['title']); ?>
if the string is greater than the specific number it'll replace 3 dots.
I hope this helps =)
?>
david at ethinkn dot com (2003-07-05 17:36:58)
Here is a simple function to shorten a string and add an ellipsis
<?php
/**
* truncate() Simple function to shorten a string and add an ellipsis
*
* @param string $string Origonal string
* @param integer $max Maximum length
* @param string $rep Replace with... (Default = '' - No elipsis -)
* @return string
* @author David Duong
**/
function truncate ($string, $max = 50, $rep = '') {
$leave = $max - strlen ($rep);
return substr_replace($string, $rep, $leave);
}
echo truncate ('akfhslakdhglksjdgh', 10, '...');
// Returns akfhsla... (10 chrs)
?>
thomasNOSPAM at sportentranceNOSPAM dot com (2002-10-08 15:01:29)
To abbreviate links into '...' if they outreach a certain amount of space; use the preg_replace function instead.
For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:
asuming the raw material is stored in $unedited;
$edited = preg_replace("/(>)([[:print:]]{52,})(<)/e", "'\\1'.substr_replace('\\2 ', '...', '48').'\\3'", $unedited);
echo $edited;
This will shorten strings longer than 52 characters into 51 characters, with the last being three dots...
klaas at group94 dot com (2002-02-13 10:38:37)
THE DOT DOT DOT ISSUE
PROBLEM:
You want to abbreviate a string.
E.g. You want "BritneySpears" to show as "BritneySpe...", being only the ten first characters followed by "..."
SOLUTION:
<?
$oRIGINAL = "BritneySpears";
$sHORTER = substr_replace($oRIGINAL, '...', 10);
echo ($sHORTER);
?>
This will result in BritneySpe...
(2001-09-28 20:30:51)
If you would like to remove characters from the start or end of a string, try the substr() function.
For example, to remove the last three characters from a string:
$string = "To be or not to be.";
$string = substr ($string, 0, -3);
mrbrown8 at juno dot com (2001-04-16 12:16:50)
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.
$var = 'ABCDEFGH:/MNRPQR/';
/* Should return ABCDEFGH:/testingRPQR/ */
echo substr_replace ($var, 'testing', 10, 2);
jgainey at infoave dot net (2001-03-13 18:29:31)
[Editor's note: for a much simpler solution, use number_format()]
I had a situation in which I needed to add a comma to the third position of a number(the price of something).
<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>
the result would be 12,000
the -3 counts from right to left. a regular 3 would count from left to right
I hope this helps...