PHP 7.0.26 Released

substr_replace

(PHP 4, PHP 5, PHP 7)

substr_replaceReplace text within a portion of a string

Descrierea

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

Parametri

string

The input 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

The replacement string.

start

If start is non-negative, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

length

If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Valorile întoarse

The result string is returned. If string is an array then array is returned.

Exemple

Example #1 Simple substr_replace() examples

<?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'0strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var'bob'00) . "<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";
?>

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'33))."\n";

// A more complicated case where each replacement is different.
$replace = array('AAA''BBB''CCC');
echo 
implode('; 'substr_replace($input$replace33))."\n";

// Replace a different number of characters each time.
$length = array(123);
echo 
implode('; 'substr_replace($input$replace3$length))."\n";
?>

Exemplul de mai sus va afișa:

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

Note

Notă: Această funcție acceptă și date binare.

A se vedea și

add a note add a note

User Contributed Notes 31 notes

up
16
elloromtz at gmail dot com
7 years ago
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
?>
up
6
juichenieder-phnet at yahoo dot co dot uk
8 years ago
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.
up
3
William Barry
9 years ago
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.
up
4
billg AT microsoft.com
8 years ago
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);
    }
}

?>
up
2
eblejr AT phrebh DOT com
9 years ago
PHP version of Java's removeCharAt() function:

<?php
function removeCharAt($str, $int){
  return
substr_replace($str,"",$int,1);
}
?>
up
1
Thijs Wijnmaalen (thijs[at]nllinux.nl)
13 years ago
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;
}
?>
up
2
den dot gierling at web dot de
7 years ago
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;
}
?>
up
2
kalim dot fleet at gmail dot com
8 years ago
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"

?>
up
2
hermes at andycostell dot com
12 years ago
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);
up
3
ivijan dot stefan at gmail dot com
3 years ago
I have a little function that works like substr_replace ()  what I use for some purpose. Maybe someone needs it.

<?php
function putinplace($string=NULL, $put=NULL, $position=false)
{
   
$d1=$d2=$i=false;
   
$d=array(strlen($string), strlen($put));
    if(
$position > $d[0]) $position=$d[0];
    for(
$i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
    for(
$i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
    return
$string;
}

// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) );
?>

RESULT: My dog don't love postman

This is a small powerful function that performs its job flawlessly.
up
2
chuayw2000 at hotmail dot com
11 years ago
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);
            }
        }
    }
}
?>
up
1
david at ethinkn dot com
14 years ago
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)

?>
up
1
danieldoorduin at hotmail dot com
12 years ago
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
up
0
Hayley Watson
1 month ago
See array_splice if you want to do this sort of thing to an array.
up
1 years ago
<?php

function (, strlen = 10, $rep = '/.../') {
  if (
$i if (!in_array(; strlen $trunc/.../'strlen > mb_strlen(; $rep strlen = mb_strlen(;         strlen >= /.../'; );
        &rd">,
$rep = ; ssefula verys is a aultt">/d">);
        &rd">,
strlen = $d2);
        }
      }
    &rd">,
= strlen ) - /.../'; // numbalaslc>$maxtoekeepbsp; }
    &rd">,
$start = null$maxChars= $d2; $posctiolt">$cuttrn string
     
= = $d2; $posfrom uld$ctiolop$cuttrn string
     
substr_replace(10, 10, $start, -$d2; );
  &t">$d2
; 10;   }
}

echo
(, , ''; echo (, , ''; echo (, , ''; echo ('abcdefghijklmnopqrstksjdgh', 10, ''; ('abcdefghijklmnopqrstksjdgh'; stt;?php

?>
up
14 years ago
<?php$pray_s>$rep = "'"$rep = substr_rstrlen (10, , -, 10= r />}
&"ord">,
(10, , -, 10= &ode"strinn be error.>?>
up
14 years ago
s know";//the sie on to longermax. fixediversfor:


&l t;?php
function treplace($string, $max = 10, $rep = ''));
    if (
mb_strlen($string$rep + mb_strlen($rep));
  &{ d">));
  &
    return
$string));
  &} d">));
  &eturn
$leave = $max - strlen ($rep));
    return
substr_replace($string, $rep, $leave));} t;?php
< t;?phpTo pre/man't witfit">t">/assfunce i>Thics a ite="50mnote:

/> * tru[fit">t">], 30, ring" .thld(explde"('.', [fit">t">]w))span>
up
14 years ago

<?phpnbsp; nbsp; &auls="dnleave = (["'", "'", $string);
?>
trinIsmeonediiou wabitfast, tringccept pretty much s a input.nbsp; &Toeeedgexiabon'n tt doesn'tsefulsimit-stc>$ma) == 0.nbsp; &Iicsme="Veplace wis, tdm've dly pretty genrible-lookhe sode", found s quititfastnstead:

<?php

function ($string, )
{
    rissetp; if (
, 10- (, 10, "'", substr($string, , $d2(, 10, mb_strlen(, , 10$string;
}

?>
Acc="ker strimy ted measures="cs,mnoeeedgexairmONLYtfaster), busefulsimit-stc>$ma) == 1 &nbsf it's libyte s,imy roult"enhas aster.nbsp; &Woundat id that?nbsp; &Le (ifsayice if you waedmon't witperiod,mnoeelassa trin with $ma("Ihere wis, ="50,mnolass=smeat..!?", ".?!")ord">);Tw";//t_padSimple funcreatesstlonger seq="/airmified ltoe witten a stoundcontainst witer of chau wabitedmon'dlace()consist a sons=soft witfirstter of chauoft wat"ten a :rd">);Tw";inputnhas".,!"rd">);Tw";outputnhas". idrd">);Tw";//ttrSimple funcranslatesst a er of charairm witten a -to-be-proc fledi("Ihere wis. id)t wat"also occurairm witinputn(".,!")ltoe witer of charairm wittt">//lt">$posirm witoutputn(". id).nbsp; &Irmauheroesnds:rd">);Ihere wis, ="50,mnolass=smeat..!?rd">);belasesrd">);Ihere wis. ="50.mnolass=smeat...ameter.F/>Orly,t witfirstter of chaufrom witinputn(".,!")lwhich happ ssu wabi, tgain,t witperiod,mhasedmon'dufrom wat"ten a void wittensubstr_recs a:rd">);Ihere wise="50mnolass=smeat?rd">);Tw";imple funmeone wact">//iseac>$maxe PHat"leastmat";
, = 1
<0s9ong>14 years ago
tdSimple fbelowte"howevn>, I1 &u tri few; riuewisParticularass_splicehult"ndcoef yo wamfsahult"any ookhld$opSimpuat">$posiid (?, !, ?!?, --, te", te, ;, etc.(10 chrs)
$p(o waliceincludeposirm w$nSimpuat">$pt"ten a elow)sa trin nhatgtesnd add a"50Solt"ev">s id axe Pnd add a""Vepla3 hotwis2 hotwis4 hotwis sest wabitedmon'din nhre-atgedannstead:

<?php
function treplace(((= = (=   if (mb_strlen(> = substr(= 10, = substr(= 10//">substr(= $p_s>$rep = "'"; $pyice if yitedmon;
}

((  &eturn $maxChars=10));
  &
 ?m length
       
substr(= 10, -((  &eturn $maxChars));
  &
 :>}

= ).;
n
= substr(=   return }
?>
th utexiabonrSimple funault">e Pr&u tref with'dlace_splice if you efault">tPr&u tref wtin th (i"5"H adant to i ssuncate longe" --eywor"H adant to akfncate longe" )funce i>Tus"50mno (requires50mnoefault">tdSimple )stnstead:

<?php
function treplace(, , =   &eturn $start = treplace(treplace(, mb_strlen(= $d2, "'", = $d2, "'");
 word">,
$start = treplace((treplace((, mb_strlen(= $d2, "'", = $d2, "'");
    return
).).}
up
down
12 years ago
$repe";//the siatgedy swardstef withld$orm witten annstead:
s know";//thewasa st are tou wised y ( &nbubstass>tPrticth previewormaa website)th uteproblemewasa wamyw";//thewasasometimesiss=f waare t stripe";s thatgedirm wfault">$repe";//th50SolIe rtitla) Simple funcneed to fers as substr_osimywwebsitestnstead:
 if(ulsimit-fault") eywor$limitey{ywsiti);
 );
   ant for substr_faulp_tagw(efault"),efaul,efault,$limiteeyord">);
 eynbsp; ywsiti);
 );
   efault"eyord">);
 eeyword" ;nnstead:
<3trong>12 years ago
 w y Ytfastepriochau 4.3.5 astef w elow">//tt's lclad.tnstead:
) {
&(fulsimitumbala) eywor$ent )umbala= for php;efau, 0,r$ent )u.rss". eyord">);
<3trong>12 years ago
t;Tw";imple fre-dtmat"strlw ysi  esstlongestnstead:

<?php
function (substr, , = mb_strlen(> /.../'strlen = mb_strlen("'");
 >    &rd">,
$i = substrb_strlen(substr, "'", $max - "'");
    }
 eynbsp; return
10}
up
down
1
14 years ago
$rep!")ltefauat.nbsp;efaule ouldcnee prentactly isola mufauimnt inximuyd$of;//the  edat.nbsp;);Tw"izeld$orm w-fault">$repe siirrelevif yrairmWounett'minat">$.tnstead:
f(ywolongbe aelow)sopert">e Psto lultdexiaboat.nbsp;Meanen 'dt;Tw"izeld$orm w-fault">$repe siunct/spandhaufrom wefau,"dnmrmWourm wfanbspedw";//the siith alvoid winximuyd$oefauannstead:

<?php
function treplace($string, $max = 10, $repe_s>$rep = '')
{
    if (
mb_strlen($string, ''  { d">));
  &
    return
$string);
    }
 word">,
$leave = $max - strlen ($rep"ng">"'");
    return
substr_replace($string, $rep"ng">"'", $leave}
up
down
1
<5srong>14 years ago
tPwitten annsteaE.g. Yice if y"BritneySpong>""d$cthow Pst"BritneySpos". ,lbest a sons0mnoelt"itfirstter of cs followbe ayhas". idrd">idrd">SOLUTION:d:

= $stringyword">($i = substrb_strlen($d2, "'", 10(10}
?>
1
<6srong>14 years ago



1
<3trong>12 years ago

<?php
function (substr, , = mb_strlen(d">,         strlen = mb_strlen("'");
 >     
substrb_strlen(substr, "'", $max - "'");
    }
}
up
down
1
<5srong>14 years ago
tlinkhara u , ring_spknoytitoreamuch ceronta amounts=so>fubstead.tnstead:
tlicfgrabbedirm wheadlinesld$om news squiti&nbus"5>$pyicrmy te066& a trin wlineslPrea s are stnstead:
up
1
strong>12 years ago
1
<6srong>14 years ago
$repe sincatto longinximu,a sons0mnoinximuyent" chauoeac>$mPreaasedmon'dufro";//the, tri thof fault">$repe siutputneitwy6lt">st, trubstri&nbsliimit-fault") to inr"leedfe:


1
14 years ago
stolongb50mno :d:

<?phpnbsp;     function substr_replace($string, $rep"ng">"'", "'", , "'", $string, "'"strlen = "'"strlen $string);
 >   ifeyword">(
$start 10, strlen mb_strlen($string+ "'");
 [at.]}
}
up
down
1
8s9ong>14 years ago
f simple e'dlace_t ookhacteameulse="5suncts=sormem wrepea bdiiouo falaitoiroafaot"any sensat"str n00b. Ns=f waI amstmatanymore'dlaceIf enouyI'dceddfa1ss=eme fumno topic myself,utnehopesa wadiimight helpIrmauhs unduhst, trub/thsfsunitdowabetf c..amete.amete"htme (a"ndcgccepm watott">eois adn tt know Pbito, = 1suret" chou us"5of towo enou; Yice i>Tampualasspu s a 854ideq="iter of chaitoid$om alibyt ayhncherrecen a stou";//the,sf enouydiiwstrmP farray. Exa is :; toIahult"know";//the$sa= 'lt"',; &Ii>Tus"5$s[0]t"strmpualassgeeritoidsons0mnoitfirstter of chauoft wat"ten 30,c'.; Tus"50m watttt">tencipl w elow'dlaceIfjusp"us"5suncopt"sti=ert">atanenouyao";//the, triddtoe witer of cha)ltoe witoutpuvaliablestmatayhtmatuntilom weaef hy6687msh tebe nhreachadst&nbuntilom withld$orm witten annstead:
ThelpItotttmatito!nnstead:

<?phlt;?php
function treplace($string,   &eturn ($string, '');
 word">,
(, '');
 foreyword">(
strlen 10strlen strlen strlen mb_strlen($string$string$string= $string$string);
    }
 eynbspeyword">(
''>;
}

$rep = ''treplace($string, ''''treplace($string, ''}

eddfa1ss=e> &padiv> > sepage=>