search for in the  
<substr_replacetrim>
Last updated: Thu, 19 May 2005

substr

(PHP 3, PHP 4, PHP 5)

substr -- Return part of a string

Description

string substr ( string string, int start [, int length] )

substr() returns the portion of string specified by the start and length parameters.

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

Example 1. Basic substr() usage

<?php
echo substr('abcdef', 1);    // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achived using "curly braces"
$string = 'abcdef';
echo
$string{0};                // a
echo $string{3};                // d
echo $string{strlen($string)-1}; // f

?>

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

Example 2. Using a negative start

<?php
$rest
= substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than or equal to start characters long, FALSE will be returned.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

Example 3. Using a negative length

<?php
$rest
= substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns ""
$rest = substr("abcdef", -3, -1); // returns "de"
?>

See also strrchr(), substr_replace(), ereg(), trim(), mb_substr() and wordwrap().



User Contributed Notes
substr
fanfatal at fanfatal dot pl
17-May-2005 05:38
Sorry for my misteake in previous function - can u change this line:

<?php
// ... old
$pattern = str_replace(chr(1),'(.*?)',preg_quote($clean));

// ... the new one
$pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
// ...
?>

I will be glad ;]
fanfatal at fanfatal dot pl
17-May-2005 01:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags

<?php

/**
 * string csubstr ( string string, int start [, int length] )
 *
 * @author FanFataL
 * @param string string
 * @param int start
 * @param [int length]
 * @return string
 */
function csubstr($string, $start, $length=false) {
  
$pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
  
$clean = preg_replace($pattern, chr(1), $string);
   if(!
$length)
      
$str = substr($clean, $start);
   else {
      
$str = substr($clean, $start, $length);
      
$str = substr($clean, $start, $length + substr_count($str, chr(1)));
   }
  
$pattern = str_replace(chr(1),'(.*?)',preg_quote($clean));
   if(
preg_match('/'.$pattern.'/is', $string, $matched))
       return
$matched[0];
   return
$string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
mike at go dot online dot pt
07-May-2005 10:15
pinetree822 at yahoo dot co dot kr
04-May-2005 01:30
//Title : mb Character Cutting& Convert
//BugsPleaseEmailMe : pinetree822@yahoo.co.kr
//home;bitmore.co.kr
//Test IN PHP Version 4.3.1-4.3.7
//OS Linux,Winodow2003
//Browser explore 6.0.3790.0

show script url<br>
http://www.bitmore.co.kr/test-module/cut_mbstring.php<br>
matt at spcan dot com
03-May-2005 01:47
substr($lbar_html,0,-2); // does not work

and

substr($lbar_html, 0, -2); // works as expected

do not work the same.
woutermb at gmail dot com
21-Mar-2005 01:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

<?php

function text($string,$limit=20,$chop=10){

$text = explode(" ",$string);
while(list(
$key, $value) = each($text)){
  
$length = strlen($value);
   if(
$length >=20){
       for(
$i=0;$i<=$length;$i+=10){
          
$new .= substr($value, $i, 10);
          
$new .= " ";
       }
        
$post .= $new;
   }
   elseif(
$length <=15){
      
$post .= $value;
   }
  
$post .= " ";
}
return(
$post);
}

// for example, this would return:
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);

echo(
$output); // "Well this text doesn't get cup up, yet thiss sssss sssss sssss sssss sss one does."
?>

I hope it was useful.. :)
vampired64 at gmail dot com
14-Mar-2005 03:28
an easy way to return a file size to 1 decimal place and MB

<?
$size
= filesize("filename.jpg"); // get size
$size = $size/1024; // convert to MB
$pos = strpos(".",$size); // get dot pos
$size = substr($size,0,$pos+3); // sub-strng it
?>
steve at unicycle dot co dot nz
13-Mar-2005 11:34
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
cody at apparitiondesigns dot com
10-Mar-2005 03:02
I don't know if I didn't realize this because I'm not very smart - or if i just over looked it, but the string needs to be a string.  Not an integer.

ex.

<?php
$var
= 12345;
  echo
$var{0}; // outputs nothing at all

$var = '12345';
  echo
$var{0}; // out puts 1
?>
Matias from Argentina
24-Feb-2005 02:55
Hello,
Here you are a function to format your
numeric strings. Enjoy it.

<?php
function str_format_number($String, $Format){
   if (
$Format == '') return $String;
   if (
$String == '') return $String;

  
$Result = '';
  
$FormatPos = 0;
  
$StringPos = 0;
   While ((
strlen($Format) - 1) >= $FormatPos){
      
//If its a number => stores it
      
if (is_numeric(substr($Format, $FormatPos, 1))){
          
$Result .= substr($String, $StringPos, 1);
          
$StringPos++;
      
//If it is not a number => stores the caracter
      
} Else {
          
$Result .= substr($Format, $FormatPos, 1);
       }
      
//Next caracter at the mask.
      
$FormatPos++;
   }

   return
$Result;
}

// For phone numbers at Buenos Aires, Argentina
// Example 1:
  
$String = "541143165500";
  
$Format = "+00 00 0000.000";
   Echo
str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 2:
  
$String = "541143165500";
  
$Format = "+00 00 0000.0000000";
   Echo
str_format_number($String, $Format); // Returns "+54 11 4316.5500"

// Example 3:
  
$String = "541143165500";
  
$Format = "+00 00 0000.000 a";
   Echo
str_format_number($String, $Format); // Returns "+54 11 4316.550 a"

?>

How it works explanation:

str_format_number($String, $Format)
Spects two parameters $String and $Format,
both should be strings.
$String: coulbe any kind of data type,
but it's oriented to numeric string, like
phone numbers.
$Format: should be a conjunction between
numbers (any one) and others caracters.

str_format_number takes each caracter
of $Format, if it isn't a number stores
it to be returned later, but if it is a
number takes the caracter of $String
placed in the position corresponding to
the amount of numbers in $Format so far
starting from zero.

If $Format has less numbers than $string
caracters the rest of the caracters at
the end of $String should be ignored.
If $Format has more numbers than $string
caracters the no caracter will be used,
so those will be ignored.
crashmanATgreenbomberDOTcom
21-Feb-2005 08:34
A fellow coder pointed out to me that $string{-n} will no longer return the character at postion -n is. Use $string{strlen($string) - n) instead.
andrewmclagan at gmail dot com
20-Feb-2005 03:58
Hi there here is a little function i wrote to limit the number of lines in a string, i could not find anything else like it out there   

function lineLimiter ($string = "", $max_lines = 1) {
  
         $string = ereg_replace("\n", "##", $string);
  
         $totalLines = (substr_count($string, '##') + 1);
  
         $string = strrev($string);
  
         $stringLength = strlen($string);
                    
         while ($totalLines > $max_lines) {
             $pos = 0;
             $pos = strpos ( $string, "##") + 2;
             //$pos = $pos - $stringLength;
             $string = substr($string, $pos);
             $totalLines--;   
         }
         $string = strrev($string);
         $string = ereg_replace("##", "\n", $string);
         return $string;
   }
Robert
13-Feb-2005 10:36
It is also good to use substr() to get a file extension when manipulating with files. For example:

<?php
$dir
= "/full/path/to/folder";
if(
is_dir($dir))
{
  if(
$dh = opendir($dir))
  {
   while((
$file = readdir($dh)) !== false)
   {
     if(
substr($file,strlen($file)-4,4) == ".txt")
     {
       echo
"Filename: $file<br/>\n";
     }
   }
  
closedir($dh);
  }
  else
  {
   echo
"Cannot open directory";
  }
}
else
{
  echo
"Cannot open directory";
}
?>

Hopefully this helps
mancini at nextcode dot org
05-Feb-2005 05:10
here are two functions to shrink a string to specified lenght , normally (stri...) or reversed (...ing)

<?php

//limit chars
 
function limitch($value,$lenght){
         if (
strlen($value) >= $lenght ){       
                
$limited = substr($value,0,$lenght);
                
$limited .= "...";                 
         }
         return
$limited;
  }
//limit chars reversed
 
function limitchrev($value,$lenght){
         if (
strlen($value) >= $lenght ){
                
$start = strlen($value)- $lenght;
                
$limited = "...";                 
                
$limited .= substr($value,$start,$lenght);
         }
         return
$limited;
  }
 
?>
vitalic#pisem.net
15-Dec-2004 05:26
Split $string after each $pos, by $space
Example: <?php spaceStr('1836254','-',3); ?>
Would return '183-625-4';

<?php
function spaceStr($string,$space,$pos)
{
      
$cpos=$pos;
       while (
$cpos<strlen($string))
       {
        
$string=substr($string,0,$cpos).$space.substr($string,$cpos);
        
$cpos+=strlen($space)+$pos;
       };
       return
$string;
}

?>
kovacsendre at no_spam_thanks_kfhik dot hungary
02-Nov-2004 09:38
Here are the replacement functions for substr() and strlen() I use when support for html entities is required:

<?php

function html_strlen($str) {
 
$chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  return
count($chars);
}

function
html_substr($str, $start, $length = NULL) {
  if (
$length === 0) return ""; //stop wasting our time ;)

  //check if we can simply use the built-in functions
 
if (strpos($str, '&') === false) { //No entities. Use built-in functions
  
if ($length === NULL)
     return
substr($str, $start);
   else
     return
substr($str, $start, $length);
  }

 
// create our array of characters and html entities
 
$chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
 
$html_length = count($chars);

 
// check if we can predict the return value and save some processing time
 
if (
       (
$html_length === 0) /* input string was empty */ or
       (
$start >= $html_length) /* $start is longer than the input string */ or
       (isset(
$length) and ($length <= -$html_length)) /* all characters would be omitted */
    
)
   return
"";

 
//calculate start position
 
if ($start >= 0) {
  
$real_start = $chars[$start][1];
  } else {
//start'th character from the end of string
  
$start = max($start,-$html_length);
  
$real_start = $chars[$html_length+$start][1];
  }

  if (!isset(
$length)) // no $length argument passed, return all remaining characters
  
return substr($str, $real_start);
  else if (
$length > 0) { // copy $length chars
  
if ($start+$length >= $html_length) { // return all remaining characters
    
return substr($str, $real_start);
   } else {
//return $length characters
    
return substr($str, $real_start, $chars[max($start,0)+$length][1] - $real_start);
   }
  } else {
//negative $length. Omit $length characters from end
    
return substr($str, $real_start, $chars[$html_length+$length][1] - $real_start);
  }

}

?>

Example:
 
html_substr("&aacute;bla&#54;bla", 1, 4) -> "bla&#54;"

If you happen to find any bugs, please let me know.
Gordon Axmann
30-Aug-2004 01:33
Two very nice and practical functions:

1. Checks if a string ($needle) turns up at the BEGINNING of another string ($hay):

2. Checks if a string ($needle) appears at the END of another string ($hay):

<?php
function isstartstring($hay,$needle,$casesensitive=true) { // prüft ob ein string am Anfang vorkommt
if (!$casesensitive) {
  
$needle=strtolower($needle);
  
$hay=strtolower($hay);
   }
return (
substr($hay,0,strlen($needle))==$needle);
}

function
isendstring($hay,$needle,$casesensitiv=true) { // prüft ob ein string am Ende vorkommt
if (!$casesensitive) {
  
$needle=strtolower($needle);
  
$hay=strtolower($hay);
   }
return (
substr($hay,-strlen($needle))==$needle);
}
?>
lmak at NOSPAM dot iti dot gr
17-Aug-2004 01:59
Regarding windix's function to handle UTF-8 strings: one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8 (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32). This way the function works for other encodings too (like Greek for example).

The modified function would read like this:

<?php
function utf8_substr($str,$start)
{
  
preg_match_all("/./u", $str, $ar);

   if(
func_num_args() >= 3) {
      
$end = func_get_arg(2);
       return
join("",array_slice($ar[0],$start,$end));
   } else {
       return
join("",array_slice($ar[0],$start));
   }
}
?>
squeegee
10-Aug-2004 09:34
php equivalent of Javascript's substring:

<?php

function substring($str,$start,$end){
   return
substr($str,$start,($end-$start));
}

?>
fox at conskript dot server
10-Aug-2004 06:01
Here's a little bit of code to chop strings (with html tags) around a specified length while making sure no html tags are chopped. It also prevents chopping while a tag is still open.

Note: this will only work in xhtml strict/transitional due to the checking of "/>" tags and the requirement of quotations in every value of a tag. It's also only been tested with the presence of br, img, and a tags, but it should work with the presence of any tag.

<?php
function html_substr($posttext, $minimum_length, $length_offset) {
  
// The approximate length you want the concatenated text to be
  
$minimum_length = 200;
  
// The variation in how long the text can be
   // in this example text length will be between 200-10=190 characters
   // and the character where the last tag ends
  
$length_offset = 10;
  
// Reset tag counter & quote checker
  
$tag_counter = 0;
  
$quotes_on = FALSE;
  
// Check if the text is too long
  
if (strlen($posttext) > $minimum_length) {
      
// Reset the tag_counter and pass through (part of) the entire text
      
for ($i = 0; $i < strlen($posttext); $i++) {
          
// Load the current character and the next one
           // if the string has not arrived at the last character
          
$current_char = substr($posttext,$i,1);
           if (
$i < strlen($posttext) - 1) {
              
$next_char = substr($posttext,$i + 1,1);
           }
           else {
              
$next_char = "";
           }
          
// First check if quotes are on
          
if (!$quotes_on) {
              
// Check if it's a tag
               // On a "<" add 3 if it's an opening tag (like <a href...)
               // or add only 1 if it's an ending tag (like </a>)
              
if ($current_char == "<") {
                   if (
$next_char == "/") {
                                      
$tag_counter++;
                   }
                   else {
                      
$tag_counter = $tag_counter + 3;
                   }
               }
              
// Slash signifies an ending (like </a> or ... />)
               // substract 2
              
if ($current_char == "/") $tag_counter = $tag_counter - 2;
              
// On a ">" substract 1
              
if ($current_char == ">") $tag_counter--;
              
// If quotes are encountered, start ignoring the tags
               // (for directory slashes)
              
if ($current_char == "\"") $quotes_on = TRUE;
           }
           else {
              
// IF quotes are encountered again, turn it back off
              
if ($current_char == "\"") $quotes_on = FALSE;
           }
                          
          
// Check if the counter has reached the minimum length yet,
           // then wait for the tag_counter to become 0, and chop the string there
          
if ($i > $minimum_length - $length_offset && $tag_counter == 0) {
              
$posttext = substr($posttext,0,$i + 1) . "...";
               return
$posttext;
           }
       }
   }
             return
$posttext;
}
aidan at php dot net
10-Jun-2004 08:03
Here is a nifty function to shorten long strings, with a variety of formatting options.

http://aidan.dotgeek.org/lib/?file=function.str_chop.php
biohazard at online dot ge
15-May-2004 03:55
may be by following functions will be easyer to extract the
needed sub parts from a string:

 after ('@', 'biohazard@online.ge');
 returns 'online.ge'
 from the first occurrence of '@'

 before ('@', 'biohazard@online.ge');
 returns 'biohazard'
 from the first occurrence of '@'

 between ('@', '.', 'biohazard@online.ge');
 returns 'online'
 from the first occurrence of '@'

 after_last ('[', 'sin[90]*cos[180]');
 returns '180]'
 from the last occurrence of '['

 before_last ('[', 'sin[90]*cos[180]');
 returns 'sin[90]*cos['
 from the last occurrence of '['

 between_last ('[', ']', 'sin[90]*cos[180]');
 returns '180'
 from the last occurrence of '['
 

<?

  
function after ($this, $inthat)
   {
       if (!
is_bool(strpos($inthat, $this)))
       return
substr($inthat, strpos($inthat,$this)+strlen($this));
   };

   function
after_last ($this, $inthat)
   {
       if (!
is_bool(strrevpos($inthat, $this)))
       return
substr($inthat, strrevpos($inthat, $this)+strlen($this));
   };

   function
before ($this, $inthat)
   {
       return
substr($inthat, 0, strpos($inthat, $this));
   };

   function
before_last ($this, $inthat)
   {
       return
substr($inthat, 0, strrevpos($inthat, $this));
   };

   function
between ($this, $that, $inthat)
   {
     return
before($that, after($this, $inthat));
   };

   function
between_last ($this, $that, $inthat)
   {
     return
after_last($this, before_last($that, $inthat));
   };

  
// USES
  
function strrevpos($instr, $needle)
   {
      
$rev_pos = strpos (strrev($instr), strrev($needle));
       if (
$rev_pos===false) return false;
       else return
strlen($instr) - $rev_pos - strlen($needle);
   };

?>
phplist at boonedocks dot net
28-Aug-2003 03:39
If 'start' is negative and greater than the length of the string, PHP seems to return the first 'length' characters of the string. For example, substr('test',-10,1) returns 't'.
05-Jul-2003 07:39
If you want to substring the middle of a string with another and keep the words intact:

<?php
/**
 * Reduce a string by the middle, keeps whole words together
 *
 * @param string $string
 * @param int $max (default 50)
 * @param string $replacement (default [...])
 * @return string
 * @author david at ethinkn dot com
 * @author loic at xhtml dot ne
 * @author arne dot hartherz at gmx dot net
 */

function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
  
$strlen = strlen($string);

   if (
$strlen <= $max)
       return
$string;

  
$lengthtokeep = $max - strlen($rep);
  
$start = 0;
  
$end = 0;

   if ((
$lengthtokeep % 2) == 0) {
      
$start = $lengthtokeep / 2;
      
$end = $start;
   } else {
      
$start = intval($lengthtokeep / 2);
      
$end = $start + 1;
   }

  
$i = $start;
  
$tmp_string = $string;
   while (
$i < $strlen) {
       if (
$tmp_string[$i] == ' ') {
          
$tmp_string = substr($tmp_string, 0, $i) . $rep;
          
$return = $tmp_string;
       }
      
$i++;
   }

  
$i = $end;
  
$tmp_string = strrev ($string);
   while (
$i < $strlen) {
       if (
$tmp_string[$i] == ' ') {
          
$tmp_string = substr($tmp_string, 0, $i);
          
$return .= strrev ($tmp_string);
       }
      
$i++;
   }
   return
$return;
   return
substr($string, 0, $start) . $rep . substr($string, - $end);
}

echo
strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30) . "\n";
// Returns: ABCDEEF GHIJK[...]asdf sadf sad s (33 chrs)
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30, '...') . "\n";
// Returns: ABCDEEF GHIJK...asdf sadf sad s (32 chrs)
?>

<substr_replacetrim>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT