PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

substr> <substr_count
Last updated: Fri, 11 Apr 2008

view this page in

substr_replace

(PHP 4, PHP 5)

substr_replace — Remplace un segment dans une chaîne

Description

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

substr_replace() remplace un segment de la chaîne string par la chaîne replacement . Le segment est délimité par start et éventuellement par length . La chaîne de résultat est retournée. Si string est un tableau, alors un tableau est retourné.

Si start est positif, le remplacement se fera à partir du start -ième caractère de string .

Si start est négatif, le remplacement se fera à partir du start -ième caractère en partant de la fin de la chaîne string .

Si length est fourni et positif, il représentera la longueur du segment de code remplacé dans la chaîne string . S'il est négatif, il représentera la longueur du segment remplacé, mais compté dans l'ordre inverse de la chaîne string . S'il est omis, il prendra la valeur par défaut de la taille de la chaîne, et remplacera tout jusqu'à la fin de la chaîne string . Bien sûr, si length vaut 0, alors, cette fonction aura comme effet d'insérer replacement dans string à la position start donnée.

Exemple #1 Exemple avec substr_replace()

<?php
$var 
'ABCDEFGH:/MNRPQR/';
echo 
"Original : $var<hr>\n";

// Remplace toute la chaîne $var par 'bob'.
echo substr_replace($var'bob'0) . "<br />\n";
echo 
substr_replace($var'bob'0strlen($var)) . "<br />\n";

// Insert 'bob' au début de la chaîne
echo substr_replace($var'bob'00) . "<br />\n";

// Remplace la séquence 'MNRPQR' par 'bob'.
echo substr_replace($var'bob'10, -1) . "<br />\n";
echo 
substr_replace($var'bob', -7, -1) . "<br />\n";

// Efface la séquence 'MNRPQR' de $var.
echo substr_replace($var''10, -1) . "<br />\n";
?>

Note: Cette fonction gère les chaînes binaires.

Voir aussi str_replace() et substr().



substr> <substr_count
Last updated: Fri, 11 Apr 2008
 
add a note add a note User Contributed Notes
substr_replace
William Barry
23-Apr-2008 12:18
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
25-Mar-2008 11:53
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
14-Feb-2008 01:07
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
13-Feb-2008 09:58
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
07-Aug-2007 12:56
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
07-Aug-2007 06:50
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
21-Mar-2007 03:00
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
09-Dec-2005 03:33
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
05-Dec-2005 08:47
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
27-Aug-2005 11:48
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
13-Jul-2005 12: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)
ogt at parasane dot com
21-Jan-2005 03:02
Actually, just a minor correction to tekrat at 2d dot com's post:

Change the code....
<?
       if(strlen($substring) < 1){
           $string = $rep;
       }else{
           $string = $substring;
       }
?>

.... into....
<?
       if(strlen($substring) >= 1){
           $string = $substring;
       }
?>

.... otherwise you'll end up with the elipses (...) for any null strings.
tekrat at 2d dot com
06-Jan-2005 08:55
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.
<?
    function truncate($substring, $max = 50, $rep = '...') {
        if(strlen($substring) < 1){
            $string = $rep;
        }else{
            $string = $substring;
        }
       
        $leave = $max - strlen ($rep);
       
        if(strlen($string) > $max){
            return substr_replace($string, $rep, $leave);
        }else{
            return $string;
        }
       
    }
?>
danieldoorduin at hotmail dot com
10-Dec-2004 02:48
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
04-Aug-2004 02:28
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
17-Jun-2004 04:34
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
13-May-2004 12:55
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
10-May-2004 02:25
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
23-Feb-2004 07:33
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)
20-Jan-2004 11:05
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
05-Nov-2003 04:40
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
05-Jul-2003 05:36
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
08-Oct-2002 03:01
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
13-Feb-2002 10:38
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...
28-Sep-2001 08:30
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
16-Apr-2001 12:16
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
13-Mar-2001 06:29
[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).
<p>
$price = "12000";<br>
$price = substr_replace ($price, ',', -3, 0)";<br>
the result would be 12,000<p>
the -3 counts from right to left. a regular 3 would count from left to right
I hope this helps...

substr> <substr_count
Last updated: Fri, 11 Apr 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites