substr

(PHP 4, PHP 5)

substrВозвращает подстроку

Описание

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

Возвращает подстроку строки string, начинающейся с start символа по счету и длиной length символов.

Список параметров

string

Входная строка. Должна содержать хотя бы один символ.

start

Если start неотрицателен, возвращаемая подстрока начинается с позиции start от начала строки, считая от нуля. Например, в строке 'abcdef', в позиции 0 находится символ 'a', в позиции 2 - символ 'c', и т.д.

Если start отрицательный, возвращаемая подстрока начинается с позиции, отстоящей на start символов от конца строки string.

Если string меньше либо содержит ровно start символов, будет возвращено FALSE.

Пример #1 Использование отрицательного параметра start

<?php
$rest 
substr("abcdef", -1);    // возвращает "f"
$rest substr("abcdef", -2);    // возвращает "ef"
$rest substr("abcdef", -31); // возвращает "d"
?>

length

Если length положительный, возвращаемая строка будет не длиннее length символов, начиная с параметраstart (в зависимости от длины string).

Если length отрицательный, то будет отброшено указанное этим аргументом число символов с конца строки string (после того как будет вычислена стартовая позиция, если start отрицателен). Если при этом позиция начала подстроки, определяемая аргументом start, находится в отброшенной части строки или за ней, возвращается false.

Если указан параметр length и является одним из 0, FALSE или NULL, то будет возвращена пустая строка.

Если параметр length опущен, то будет возвращена подстрока, начинающаяся с позиции, указанной параметром start и длящейся до конца строки.

Пример #2 Использование отрицательного параметра length

<?php
$rest 
substr("abcdef"0, -1);  // возвращает "abcde"
$rest substr("abcdef"2, -1);  // возвращает "cde"
$rest substr("abcdef"4, -4);  // возвращает false
$rest substr("abcdef", -3, -1); // возвращает "de"
?>

Возвращаемые значения

Возвращает извлеченную часть строки, или FALSE в случае возникновения ошибки или пустую строку.

Список изменений

Версия Описание
5.2.2 - 5.2.6 Если параметр start указывает на позицию с отрицательной обрезкой, возвращается FALSE. Другие версии возвращают строку с начала.

Примеры

Пример #3 Базовое использование substr()

<?php
echo substr('abcdef'1);     // bcdef
echo substr('abcdef'13);  // bcd
echo substr('abcdef'04);  // abcd
echo substr('abcdef'08);  // abcdef
echo substr('abcdef', -11); // f

// Получить доступ к отдельному символу в строке
// можно также с помощью "квадратных скобок"
$string 'abcdef';
echo 
$string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Пример #4 substr() и приведение типов

<?php
class apple {
    public function 
__toString() {
        return 
"green";
    }
}

echo 
"1) ".var_export(substr("pear"02), true).PHP_EOL;
echo 
"2) ".var_export(substr(5432102), true).PHP_EOL;
echo 
"3) ".var_export(substr(new apple(), 02), true).PHP_EOL;
echo 
"4) ".var_export(substr(true01), true).PHP_EOL;
echo 
"5) ".var_export(substr(false01), true).PHP_EOL;
echo 
"6) ".var_export(substr(""01), true).PHP_EOL;
echo 
"7) ".var_export(substr(1.2e304), true).PHP_EOL;
?>

Результат выполнения данного примера:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Ошибки

Возвращает FALSE в случае ошибки.

<?php
var_dump
(substr('a'1)); // bool(false)
?>

Смотрите также

Коментарии

Автор:
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_string0$i) . $rep;
           
$return $tmp_string;
        } 
       
$i++;
    } 

   
$i $end;
   
$tmp_string strrev ($string);
    while (
$i $strlen) {
        if (
$tmp_string[$i] == ' ') {
           
$tmp_string substr($tmp_string0$i);
           
$return .= strrev ($tmp_string);
        } 
       
$i++;
    } 
    return 
$return;
    return 
substr($string0$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)
?>
2003-07-05 20:39:10
http://php5.kiev.ua/manual/ru/function.substr.html
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'.
2003-08-28 16:39:55
http://php5.kiev.ua/manual/ru/function.substr.html
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)); 
   } 
}
?>
2004-08-17 14:59:15
http://php5.kiev.ua/manual/ru/function.substr.html
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, -1PREG_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, -1PREG_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.
2004-11-02 09:38:45
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
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;
}

?>
2004-12-15 05:26:43
http://php5.kiev.ua/manual/ru/function.substr.html
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   

<?php
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;
    }
?>
2005-02-20 03:58:12
http://php5.kiev.ua/manual/ru/function.substr.html
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.
2005-02-21 20:34:07
http://php5.kiev.ua/manual/ru/function.substr.html
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$FormatPos1))){
           
$Result .= substr($String$StringPos1);
           
$StringPos++;
       
//If it is not a number => stores the caracter
       
} Else {
           
$Result .= substr($Format$FormatPos1);
        }
       
//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.
2005-02-24 14:55:52
http://php5.kiev.ua/manual/ru/function.substr.html
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
2005-03-13 23:34:04
http://php5.kiev.ua/manual/ru/function.substr.html
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$i10);
           
$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."105);

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

I hope it was useful.. :)
2005-03-21 13:19:23
http://php5.kiev.ua/manual/ru/function.substr.html
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($patternchr(1), $string);
    if(!
$length)
       
$str substr($clean$start);
    else {
       
$str substr($clean$start$length);
       
$str substr($clean$start$length substr_count($strchr(1)));
    }
   
$pattern str_replace(chr(1),'(.*?)',preg_quote($str));
    if(
preg_match('/'.$pattern.'/is'$string$matched))
        return 
$matched[0];
    return 
$string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
2005-05-17 02:45:49
http://php5.kiev.ua/manual/ru/function.substr.html
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...

Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it... 
Enjoy it :) ...

--- Bleakwind
QQ:940641
http://www.weaverdream.com

PS:I'm sorry my english is too poor... :( 

<?php
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string$start$len$byte=3)
{
   
$str     "";
   
$count   0;
   
$str_len strlen($string);
    for (
$i=0$i<$str_len$i++) {
        if ((
$count+1-$start)>$len) {
           
$str  .= "...";
            break;
        } elseif ((
ord(substr($string,$i,1)) <= 128) && ($count $start)) {
           
$count++;
        } elseif ((
ord(substr($string,$i,1)) > 128) && ($count $start)) {
           
$count $count+2;
           
$i     $i+$byte-1;
        } elseif ((
ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
           
$str  .= substr($string,$i,1);
           
$count++;
        } elseif ((
ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
           
$str  .= substr($string,$i,$byte);
           
$count $count+2;
           
$i     $i+$byte-1;
        }
    }
    return 
$str;
}

// Test
$str "123456ֽ123456ַ123456ȡ";
for(
$i=0;$i<30;$i++){
    echo 
"<br>".bite_str($str,$i,20);   
}
?>
2005-05-25 13:11:18
http://php5.kiev.ua/manual/ru/function.substr.html
I have developed a function with a similar outcome to jay's

Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.

<?php
function limit_string($string$charlimit)
{
    if(
substr($string,$charlimit-1,1) != ' ')
    {
       
$string substr($string,'0',$charlimit);
       
$array explode(' ',$string);
       
array_pop($array);
       
$new_string implode(' ',$array);

        return 
$new_string.'...';
    }
    else
    {   
        return 
substr($string,'0',$charlimit-1).'...';
    }
}
?>
2005-06-07 06:43:41
http://php5.kiev.ua/manual/ru/function.substr.html
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:

<?php
   
// both lines will output the 3rd character
   
echo substr($my_string21);
    echo 
$my_string{2}; 
?>

curly braces syntax is faster and more readable IMHO..
2005-06-07 23:31:26
http://php5.kiev.ua/manual/ru/function.substr.html
I needed to cut a string after x chars at a  html converted utf-8 text (for example Japanese text like &#23344;&#35632;&#24368;&#33072;&#27440;&#32591;). 
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.

<?php

function html_cutstr ($str$len)
{
    if (!
preg_match('/\&#[0-9]*;.*/i'$str))
    {
       
$rVal strlen($str$len);
        break;
    }

   
$chars 0;
   
$start 0;
    for(
$i=0$i strlen($str); $i++)
    {
        if (
$chars >= $len)
        break;

       
$str_tmp substr($str$start$i-$start);
        if (
preg_match('/\&#[0-9]*;.*/i'$str_tmp))
        {
           
$chars++;
           
$start $i;
        }
    }
   
$rVal substr($str0$start);
    if (
strlen($str) > $start)
   
$rVal .= " ...";
    return 
$rVal;
}
?>
2005-06-29 11:07:36
http://php5.kiev.ua/manual/ru/function.substr.html
This function shortens the string down to maximum lengt defined in $max_lengt. If the string is longer the function finds the last occurance of a space and adds three dots at the end to illustrate that it is more text. If the string is without spaces it stops at exacly max lengt, also adding three dots. If the string is shorter than max lengt it returns the string as it is. This is useful for previewing long strings.

<?php
function str_stop($string$max_length){
    if (
strlen($string) > $max_length){
       
$string substr($string0$max_length);
       
$pos strrpos($string" ");
        if(
$pos === false) {
               return 
substr($string0$max_length)."...";
           }
        return 
substr($string0$pos)."...";
    }else{
        return 
$string;
    }
}
?>
2005-07-04 14:23:03
http://php5.kiev.ua/manual/ru/function.substr.html
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:

<?php
function utf8_substr($str,$start)
{
   
preg_match_all("/./su"$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));
   }
}
?>
2005-07-25 17:37:38
http://php5.kiev.ua/manual/ru/function.substr.html
JavaScript charAt PHP equivalent

<?php
   
function charAt($str$pos)
    {
        return (
substr($str$pos1)) ? substr($str$pos1) : -1;
    }
?>

If found, return the charecter at the specified position, otherwise return -1
2005-11-29 06:48:10
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
Here's a little addon to the html_substr function posted by fox. 

Now it counts only chars outside of tags, and doesn't cut words.

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 200$length_offset 20$cut_words FALSE$dots TRUE) {
   
   
// $minimum_length:
    // The approximate length you want the concatenated text to be   
 

    // $length_offset:
    // The variation in how long the text can be in this example text 
    // length will be between 200 and 200-20=180 characters and the 
    // character where the last tag ends

    // 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
       
$c 0;
        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 += 1;
                    }
                    else {
                       
$tag_counter += 3;
                    }
                }
               
// Slash signifies an ending (like </a> or ... />)
                // substract 2
               
if ($current_char == '/' && $tag_counter <> 0$tag_counter -= 2;
               
// On a ">" substract 1
               
if ($current_char == '>'$tag_counter -= 1;
               
// 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;
            }
           
           
// Count only the chars outside html tags
           
if($tag_counter == || $tag_counter == 0){
               
$c++;
            }           
                           
           
// 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 ($c $minimum_length $length_offset && $tag_counter == && ($next_char == ' ' || $cut_words == TRUE)) {
               
$posttext substr($posttext,0,$i 1);               
                if(
$dots){
                   
$posttext .= '...';
                }
                return 
$posttext;
            }
        }
    }   
    return 
$posttext;


?>
2005-12-14 04:54:00
http://php5.kiev.ua/manual/ru/function.substr.html
Be careful when comparing the return value of substr to FALSE. FALSE may be returned even if the output is a valid string.

substr("0", 0); // equals "0", comparision with FALSE evaluates to true, because "0" == 0 == FALSE
2006-01-04 21:22:35
http://php5.kiev.ua/manual/ru/function.substr.html
Add on to (a function originally written by) "Matias from Argentina": str_format_number function.

Just added handling of $String shorter then $Format by adding a side to start the fill and a string length to the while loop.

<?php
function str_format_number($String$Format$Start 'left'){
   
//If we want to fill from right to left incase string is shorter then format
   
if ($Start == 'right') {
       
$String strrev($String);
       
$Format strrev($Format); 
    }
    if(
$Format == '') return $String;
    if(
$String == '') return $String;   
   
$Result '';
   
$FormatPos 0;
   
$StringPos 0;
    while ((
strlen($Format) - 1) >= $FormatPos && strlen($String) > $StringPos) {
       
//If its a number => stores it
       
if (is_numeric(substr($Format$FormatPos1))) {
           
$Result .= substr($String$StringPos1);
           
$StringPos++;
           
//If it is not a number => stores the caracter
       
} else {
           
$Result .= substr($Format$FormatPos1);
        }
       
//Next caracter at the mask.
       
$FormatPos++;
    }
    if (
$Start == 'right'$Result strrev($Result);
    return 
$Result;
}
?>
2006-01-10 15:34:43
http://php5.kiev.ua/manual/ru/function.substr.html
Here's a function I wrote that'll insert a string into another string with an offset.

<?php
// $insertstring - the string you want to insert
// $intostring - the string you want to insert it into
// $offset - the offset

function str_insert($insertstring$intostring$offset) {
   
$part1 substr($intostring0$offset);
   
$part2 substr($intostring$offset);
   
   
$part1 $part1 $insertstring;
   
$whole $part1 $part2;
    return 
$whole;
}
?>
2006-02-03 20:37:41
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
a function to read in a file and split the string into its individual characters and display them as images for a webcounter.

can be used anywhere you need to split a string where a seperator is not present and versions where the str_split() function is also not present.

<?php 
//start counter
$filename "counter_file.txt";
$pathtoiamges "http://www.yoursite.com/counter/";//where is your iamges
$extension ".gif";//what filetype are your images in
//--------------do not change below this line-------------------
$counter=file_get_contents($filename);
$counter++;
$count=$counter;
$current=0;
$visit=array("");//array to hold individual characters
//split string into individual characters
//same as str_split($str) in PHP5
while (strlen($count)>0)
    {
   
$current++;
   
$visit[$current]=substr($count,0,1);//get current digit
   
$count=substr($count,1,strlen($count));//reduce number string to remove last stored digit
   
}
//display images of digits
foreach ($visit as $vis)
    {
    if (
$vis!=""){echo "<img src=\""$pathtoimages $vis . .$extension "\">";}
    }
$list fopen($filename"w+");
fwrite($list$counter);
fclose($list);
//end counter
?>

requires a file to store the counter and 10 images to represent the digits (0-9) if used as a counter.
2006-02-13 07:21:01
http://php5.kiev.ua/manual/ru/function.substr.html
<?php
//function to get a substring between between two other substrings

function substring_between($haystack,$start,$end) {
    if (
strpos($haystack,$start) === false || strpos($haystack,$end) === false) {
        return 
false;
    } else {
       
$start_position strpos($haystack,$start)+strlen($start);
       
$end_position strpos($haystack,$end);
        return 
substr($haystack,$start_position,$end_position-$start_position);
    }
}

//use of this function to get the title of an html document

$handle fopen($filename'r');
$contents fread($handlefilesize($filename));
fclose($handle);

$contents htmlspecialchars($contents);
$title substring_between($contents,'&lt;title&gt;','&lt;/title&gt;');

?>
2006-08-16 12:31:18
http://php5.kiev.ua/manual/ru/function.substr.html
This function can replace substr() in some situations you don't want to cut right in the middle of a word. strtrim will cut between words when it is possible choosing the closest possible final string len to return. the maxoverflow parameter lets you choose how many characters can overflow past the maxlen parameter.

<?php

function strtrim($str$maxlen=100$elli=NULL$maxoverflow=15) {
    global 
$CONF;
       
    if (
strlen($str) > $maxlen) {
           
        if (
$CONF["BODY_TRIM_METHOD_STRLEN"]) {
            return 
substr($str0$maxlen);
        }
           
       
$output NULL;
       
$body explode(" "$str);
       
$body_count count($body);
       
       
$i=0;
   
        do {
           
$output .= $body[$i]." ";
           
$thisLen strlen($output);
           
$cycle = ($thisLen $maxlen && $i $body_count-&& ($thisLen+strlen($body[$i+1])) < $maxlen+$maxoverflow?true:false);
           
$i++;
        } while (
$cycle);
        return 
$output.$elli;
    }
    else return 
$str;
}

?>
2006-10-15 20:47:50
http://php5.kiev.ua/manual/ru/function.substr.html
<?php

/**
 * string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
 *
 * If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
 *
 * If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
 *
 * If the first character in (string) $start or (string) $end is '-', the last occuring string will be used.
 *
 * If $ignore_case is true, substrpos will not care about the case.
 * If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
 *        Both of the above: only applies if either $start or $end are strings.
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', 5, '5');
 *        // Prints 'is a string with 01234';
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', '5', 5);
 *        // Prints '56789'
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-string')
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', true)
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', false)
 *        // Prints 's is a string with 0123456789 numbers in it and two strings.'
 *
 * Warnings:
 *        Since $start and $end both take either a string or an integer:
 *            If the character or string you are searching $str for is a number, pass it as a quoted string.
 *        If $end is (integer) 0, an empty string will be returned.
 *        Since this function takes negative strings ('-search_string'):
 *            If the string your using in $start or $end is a '-' or begins with a '-' escape it with a '\'.
 *            This only applies to the *first* character of $start or $end.
 */

// Define stripos() if not defined (PHP < 5).
if (!is_callable("stripos")) {
    function 
stripos($str$needle$offset 0) {
        return 
strpos(strtolower($str), strtolower($needle), $offset);
    }
}

function 
substrpos($str$start$end false$ignore_case false) {
   
// Use variable functions
   
if ($ignore_case === true) {
       
$strpos 'stripos'// stripos() is included above in case it's not defined (PHP < 5).
   
} else {
       
$strpos 'strpos';
    }

   
// If end is false, set it to the length of $str
   
if ($end === false) {
       
$end strlen($str);
    }

   
// If $start is a string do what's needed to make it an integer position for substr().
   
if (is_string($start)) {
       
// If $start begins with '-' start processing until there's no more matches and use the last one found.
       
if ($start{0} == '-') {
           
// Strip off the '-'
           
$start substr($start1);
           
$found false;
           
$pos 0;
            while((
$curr_pos $strpos($str$start$pos)) !== false) {
               
$found true;
               
$pos $curr_pos 1;
            }
            if (
$found === false) {
               
$pos false;
            } else {
               
$pos -= 1;
            }
        } else {
           
// If $start begins with '\-', strip off the '\'.
           
if ($start{0} . $start{1} == '\-') {
               
$start substr($start1);
            }
           
$pos $strpos($str$start);
        }
       
$start $pos !== false $pos 0;
    }

   
// Chop the string from $start to strlen($str).
   
$str substr($str$start);

   
// If $end is a string, do exactly what was done to $start, above.
   
if (is_string($end)) {
        if (
$end{0} == '-') {
           
$end substr($end1);
           
$found false;
           
$pos 0;
            while((
$curr_pos strpos($str$end$pos)) !== false) {
               
$found true;
               
$pos $curr_pos 1;
            }
            if (
$found === false) {
               
$pos false;
            } else {
               
$pos -= 1;
            }
        } else {
            if (
$end{0} . $end{1} == '\-') {
               
$end substr($end1);
            }
           
$pos $strpos($str$end);
        }
       
$end $pos !== false $pos strlen($str);
    }

   
// Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
   
return substr($str0$end);
}

?>
2006-10-19 06:19:39
http://php5.kiev.ua/manual/ru/function.substr.html
Here is also a nice (but a bit slow) alternative for colorizing an true color image:

<?php
// $colorize = hexadecimal code in String format, f.e. "10ffa2"
// $im = the image that have to be computed

$red hexdec(substr($colorize02));
$green hexdec(substr($colorize22));
$blue hexdec(substr($colorize42));

$lum_c floor(($red*299 $green*587 $blue*144) / 1000);

for (
$i 0$i $lum_c$i++)
{
 
$r $red $i $lum_c;
 
$g $green $i $lum_c;
 
$b $blue $i $lum_c;
 
$pal[$i] = $r<<16 $g<<$b;
}
$pal[$lum_c] = $red<<16 $green<<$blue;
for (
$i $lum_c+1$i 255$i++)
{
 
$r $red + (255-$red) * ($i-$lum_c) / (255-$lum_c);
 
$g $green + (255-$green) * ($i-$lum_c) / (255-$lum_c);
 
$b $blue + (255-$blue) * ($i-$lum_c) / (255-$lum_c);
 
$pal[$i] = $r<<16 $g<<$b;
}

$sy imagesy($im);
$sx imagesx($im);
for(
$y=0;$y<$sy;$y++)
{
  for(
$x=0;$x<$sx;$x++)
  {
   
$rgba imagecolorat($im$x$y);
   
$a = ($rgba 0x7F000000) >> 24;
   
$r = ($rgba 0xFF0000) >> 16;
   
$g = ($rgba 0x00FF00) >> 8;
   
$b = ($rgba 0x0000FF);

   
$lum floor(($r*299+$g*587+$b*144)/1000);

   
imagesetpixel($im$x$y$a<<24 $pal[$lum]);
  }
}
?>
2007-02-13 09:45:39
http://php5.kiev.ua/manual/ru/function.substr.html
<?php
/*
    An advanced substr but without breaking words in the middle.
    Comes in 3 flavours, one gets up to length chars as a maximum, the other with length chars as a minimum up to the next word, and the other considers removing final dots, commas and etcteteras for the sake of beauty (hahaha).
   This functions were posted by me some years ago, in the middle of the ages I had to use them in some corporations incorporated, with the luck to find them in some php not up to date mirrors. These mirrors are rarely being more not up to date till the end of the world... Well, may be am I the only person that finds usef not t bre word in th middl?

Than! (ks)

This is the calling syntax:

    snippet(phrase,[max length],[phrase tail])
    snippetgreedy(phrase,[max length before next space],[phrase tail])

*/

function snippet($text,$length=64,$tail="...") {
   
$text trim($text);
   
$txtl strlen($text);
    if(
$txtl $length) {
        for(
$i=1;$text[$length-$i]!=" ";$i++) {
            if(
$i == $length) {
                return 
substr($text,0,$length) . $tail;
            }
        }
       
$text substr($text,0,$length-$i+1) . $tail;
    } 
    return 
$text;
}

// It behaves greedy, gets length characters ore goes for more

function snippetgreedy($text,$length=64,$tail="...") {
   
$text trim($text);
    if(
strlen($text) > $length) {
        for(
$i=0;$text[$length+$i]!=" ";$i++) {
            if(!
$text[$length+$i]) {
                return 
$text;
            }
        }
       
$text substr($text,0,$length+$i) . $tail;
    } 
    return 
$text;
}

// The same as the snippet but removing latest low punctuation chars, 
// if they exist (dots and commas). It performs a later suffixal trim of spaces

function snippetwop($text,$length=64,$tail="...") {
   
$text trim($text);
   
$txtl strlen($text);
    if(
$txtl $length) {
        for(
$i=1;$text[$length-$i]!=" ";$i++) {
            if(
$i == $length) {
                return 
substr($text,0,$length) . $tail;
            }
        }
        for(;
$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
       
$text substr($text,0,$length-$i+1) . $tail;
    } 
    return 
$text;
}

/*
echo(snippet("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetwop("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea") . "<br>");
echo(snippetgreedy("this is not too long to run on the column on the left, perhaps, or perhaps yes, no idea"));
*/
?>
2007-02-14 04:20:02
http://php5.kiev.ua/manual/ru/function.substr.html
A further addition to Jean-Felix function to extract data between delimeters. 

The previous function wouldn't return the correct data if the delimeters used where long than one char. Instead the following function should do the job.

<?php
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
   
$posLeft  stripos($inputstr,$delimeterLeft)+strlen($delimeterLeft);
   
$posRight stripos($inputstr,$delimeterRight,$posLeft+1);
   return 
substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
2007-03-06 15:51:52
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
The functions submitted below are a waste of time and memory. To convert a string to an integer or a trimmed float, use the built in conversion instead of parsing the string, e.g :

<?php
$x 
"27.2400";
echo (float)
$x// 27.24
echo (int)$x// 27
?>
2007-05-10 12:08:12
http://php5.kiev.ua/manual/ru/function.substr.html
Starting from version 5.2.3 if $start is negative and larger then the length of the string, the result is an empty string, while in earlier versions the result was the string itself!

substr ("abcdef", -1000);

result in 5.2.0
'abcdef'

result in 5.2.3
''

This is a small inconsistency, one of those things that makes the life of a PHP programmer like hell.
2007-06-26 06:31:04
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
All the references to "curly braces" on this page appear to be obsolete.

According to http://us.php.net/manual/en/language.types.string.php

"Using square array-brackets is preferred because the {braces} style is deprecated as of PHP 6."

Robert Chapin
Chapin Information Services
2007-06-26 17:40:49
http://php5.kiev.ua/manual/ru/function.substr.html
If you need to divide a large string (binary data for example) into segments, a much quicker way to do it is to use streams and the php://memory stream wrapper.

For example, if you have a large string in memory, write it to a memory stream like 
<?php
$segment_length 
8192// this is how long our peice will be
$fp fopen("php://memory"'r+'); // create a handle to a memory stream resource
fputs($fp$payload); // write data to the stream
$total_length=ftell($fp); // get the length of the stream
$payload_chunk fread $fp$segment_length  );
?>

Working with large data sets, mine was 21MB, increased the speed several factors.
2007-07-30 18:06:52
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for (
$i 0$i 1500000$i++){
   
$opening substr($string,0,11);
    if (
$opening == 'Lorem ipsum'){
       
true;
    }else{
       
false;
    }
}
$endtime1 endTimer();

/* direct access */
beginTimer();
for (
$i 0$i 1500000$i++){
    if (
$string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
       
true;
    }else{
       
false;
    }
}
$endtime2 endTimer();

/* strstr access */
beginTimer();
for (
$i 0$i 1500000$i++){
   
$opening strstr($string,'Lorem ipsum');
    if (
$opening == true){
       
true;
    }else{
       
false;
    }
}
$endtime3 endTimer();

echo 
$endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
2007-08-31 06:56:23
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I prefer
<?php
function short_name($str$limit)
{
    return 
strlen($str) > $limit substr($str0$limit 3) . '...' $str;
}
?>

Now, every returned string has a maximum length of $limit chars (instead of $limit + 3).
2007-09-12 19:06:46
http://php5.kiev.ua/manual/ru/function.substr.html
Adding the $limit parameter introduced a bug that was not present in the original. If $limit is small or negative, a string with a length exceeding the limit can be returned. The $limit parameter should be checked. It takes slightly more processing, but it is dwarfed in comparison to the use of strlen().

<?php
 
function short_name($str$limit)
  {
   
// Make sure a small or negative limit doesn't cause a negative length for substr().
   
if ($limit 3)
    {
     
$limit 3;
    }

   
// Now truncate the string if it is over the limit.
   
if (strlen($str) > $limit)
    {
      return 
substr($str0$limit 3) . '...';
    }
    else
    {
      return 
$str;
    }
  }
?>
2007-09-24 13:55:03
http://php5.kiev.ua/manual/ru/function.substr.html
Because i didnt see a function that would cut a phrase from a text (article or whatever) no matter where, front/middle/end and add ... + keeping the words intact, i wrote this:

Usage:
- The parameter $value if array will need the whole text and the portion you want to start from, a string. EG: cuttext(array($text, $string), 20). If the string is "have" and is near the beginning of the text, the function will cut like "I have a car ...", if the string is in the middle somewhere it will cut like "... if you want to have your own car ..." and if its somewhere near the end it will cut like "... and you will have one."
- The $length parameter is self explanatory.

Note: if you have just a string "127hh43h2h52312453jfks2" and you want to cut it, just use the function like so: cuttext($string, 10) and it will cut it like "127hh43h2h..."

<?php

////////////////////////////////////////////////////////
// Function:         cuttext
// Description: Cuts a string and adds ...

function cuttext($value$length)
{   
    if(
is_array($value)) list($string$match_to) = $value;
    else { 
$string $value$match_to $value{0}; }

   
$match_start stristr($string$match_to);
   
$match_compute strlen($string) - strlen($match_start);

    if (
strlen($string) > $length)
    {
        if (
$match_compute < ($length strlen($match_to)))
        {
           
$pre_string substr($string0$length);
           
$pos_end strrpos($pre_string" ");
            if(
$pos_end === false$string $pre_string."...";
            else 
$string substr($pre_string0$pos_end)."...";
        }
        else if (
$match_compute > (strlen($string) - ($length strlen($match_to))))
        {
           
$pre_string substr($string, (strlen($string) - ($length strlen($match_to))));
           
$pos_start strpos($pre_string" ");
           
$string "...".substr($pre_string$pos_start);
            if(
$pos_start === false$string "...".$pre_string;
            else 
$string "...".substr($pre_string$pos_start);
        }
        else
        {       
           
$pre_string substr($string, ($match_compute round(($length 3))), $length);
           
$pos_start strpos($pre_string" "); $pos_end strrpos($pre_string" ");
           
$string "...".substr($pre_string$pos_start$pos_end)."...";
            if(
$pos_start === false && $pos_end === false$string "...".$pre_string."...";
            else 
$string "...".substr($pre_string$pos_start$pos_end)."...";
        }

       
$match_start stristr($string$match_to);
       
$match_compute strlen($string) - strlen($match_start);
    }
   
    return 
$string;
}

?>
2008-01-05 22:47:37
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I've used the between, after, before, etc functions that biohazard put together for years and they work great.  I've also added to it a new function that I use a lot and thought others might like it as well.  It uses his before/after functions so they are required to use it.

<?php
$example_html 
"<p>test1 Test2</p><title>hi there</title><p>Testing</p>";
$paragraph_text multi_between('<p>''</p>'$example_html);

//Prints an arry of:
//Array ( [1] => test1 Test2 [2] => Testing )
print_r($paragraph_text);

function 
multi_between($this$that$inthat)
{
   
$counter 0;
   while (
$inthat)
   {
     
$counter++;
     
$elements[$counter] = before($that$inthat);
     
$elements[$counter] = after($this$elements[$counter]);
     
$inthat after($that$inthat);
   }
   return 
$elements;
}
//Get the help functions from biohazard's post below.
?>
2008-02-22 19:12:03
http://php5.kiev.ua/manual/ru/function.substr.html
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (
substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
2008-02-29 19:21:51
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
Split a string to an array of strings specified by an array of lengths:

<?php
function split_by_lengths($inString$arrayLengths)
{
   
$output = array();
    foreach (
$arrayLengths as $oneLength)
    {
       
$output[] = substr($inString0$oneLength);
       
$inString substr($inString$oneLength);
    }
    return (
$output);
}
?>
split_by_lengths('teststringtestteststring', array(4,6,4,4,6)) returns:
array('test','string','test','test','string')

Don't use it on user input without some error handling!
2008-03-17 05:53:49
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
easy and quick way to limit length of a text by not cutting full words:

textLimit('some words', 7) is 'some...'

<?php
function textLimit($string$length$replacer '...')
{
  if(
strlen($string) > $length)
  return (
preg_match('/^(.*)\W.*$/'substr($string0$length+1), $matches) ? $matches[1] : substr($string0$length)) . $replacer;
 
  return 
$string;
}
?>
2008-06-03 06:13:18
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
joao dot martins at plako dot net
26-Mar-2008 09:14

ben at enemy dot dk
10-Feb-2008 05:48 

Updated function. The previous one will return empty value if the $string has no letter spaces. This is usefull if some of your strings have only one word.

<?php
function cutText($string$setlength) {
   
$length $setlength;
    if(
$length<strlen($string)){
        while ((
$string{$length} != " ") AND ($length 0)) {
           
$length--;
        }
        if (
$length == 0) return substr($string0$setlength);
        else return 
substr($string0$length);
    }else return 
$string;
}
?>
2008-06-27 16:09:31
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I wrote this simple function to limit the middle characters of a string to a specified length.

<?php
$input 
"hello world"
echo(limitchrmid($imput,10)) // hel ... rld

//limit chars middle
function limitchrmid($value,$lenght){
    if (
strlen($value) >= $lenght ){
       
$lenght_max = ($lenght/2)-3;
       
$start strlen($value)- $lenght_max;
       
$limited substr($value,0,$lenght_max);
       
$limited.= " ... ";                   
       
$limited.= substr($value,$start,$lenght_max);
    }
    else{
       
$limited $value;
    }
    return 
$limited;
}
?>
2008-07-29 14:18:40
http://php5.kiev.ua/manual/ru/function.substr.html
Here is a quick function to get the substring of a string up to and including the last occurrence of $needle

<?php
function substrtruncate($string$needle)
{
    return 
substr($string0strrpos($string$needle)+1);
}

$current_dir substrtruncate($_SERVER['SCRIPT_NAME'], '/');
?>
2008-07-31 17:17:48
http://php5.kiev.ua/manual/ru/function.substr.html
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str$amount 1$dir "right")
{
  if((
$n strlen($str)) > 0)
  {
    if(
$dir == "right")
    {
     
$start 0;
     
$end $n-$amount;
    } elseif( 
$dir == "left") {
     
$start $amount;
     
$end $n;
    }
   
    return 
substr($str$start$end);
  } else return 
false;
}
?>

Enjoy ;)
2008-08-05 10:59:53
http://php5.kiev.ua/manual/ru/function.substr.html
***Caution newbie***
To extract a file Extension this fuction could be useful.

<?php
$file_extension 
substr($filename strrpos($filename '. ') +1);
?>

Suppose your file name is Baldaris.jpeg

strrpos will return the last dot position in the string 9 so 

so the compiler will execute substr($filename , 10)

$file_extension will have value jpeg

pretty cool...

Cheer's

Baldaris
2008-08-29 03:57:24
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
<?php

function insert_substr($str$pos$substr) {
   
$part1 substr($str0, -$pos);
   
$part2 substr($str, -$pos);
    return 
$part1.$substr.$part2;
}

?>
2008-09-19 06:21:21
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
Simple use of substr to determine possession:

<?php
function possessive ($word) {
    return 
$word.(substr($word, -1) == 's' "'" "'s");
}

// Davis => Davis'
// Paul => Paul's
?>
2008-09-29 13:01:54
http://php5.kiev.ua/manual/ru/function.substr.html
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers. 
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{   
    list(
$A,$B,$C,$D)    =    explode(".",$val);
    return 
       
substr("000".$A,-3).
       
substr("000".$B,-3).
       
substr("000".$C,-3).
       
substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if(
$min<$visitor && $visitor<$max)   
    {    echo 
'Welcome !';    }
else   
    {    echo 
'Get out of here !';    }

?>
2008-10-24 17:31:36
http://php5.kiev.ua/manual/ru/function.substr.html
hi, really basic function to take blob with full http url's and turn then into "more info" links, handy for page layout etc ;)

<?php
function urltolink($data){

    while (
strpos($wdata"http")) {

   
$op=strpos($wdata"http");
   
$rdata=substr($wdata0$op);
   
$ndata=substr($wdata$opstrlen($wdata)-$op);
   
   
$cp=strpos($ndata"\n");
   
$link=substr($ndata0$cp);
   
$oc=$op+$cp;
   
$wdata=substr($wdata$ocstrlen($wdata)-$oc);
   
   
$edata=$edata."$rdata <a href=\"$link\">more info</a><br />";
    }
    return 
$edata;
}
?>
2008-10-30 18:52:16
http://php5.kiev.ua/manual/ru/function.substr.html
<?php
$cfg
[csvEnc] = '"';
$cfg[csvEsc] = '\\';
$cfg[csvTerm] = ",";

if( !
function_exists("parse_csv_aux") ){
    function 
parse_csv_aux$string ){
        global 
$cfg;
       
$product "";
       
$in_quote FALSE;
       
$skipped_quote FALSE;
        for(
$i $i strlen($string) ; $i++){
            if( 
$string{$i} == $cfg[csvEnc] ){
                if(
$in_quote){
                    if(
$skipped_quote){
                       
$product .= $cfg[csvEnc];
                       
$skipped_quote FALSE;
                    }
                    else if( !
$skipped_quote ){
                       
$skipped_quote TRUE;
                    }
                   
$in_quote FALSE;
                }
                else{
                    if(
$skipped_quote$skipped_quote FALSE;
                   
$in_quote TRUE;
                }
            }
            else if( 
$string{$i} == "," ){
                if(
$in_quote){
                   
$product .= ",";
                }
                else{
                   
$product .= " ~ ";
                }
            }
            else{
                if(
$in_quote){
                   
//$in_quote = FALSE;
                   
$product .= $string{$i};
                }
                else{
                   
$product .= $string{$i};
                }
            }
        }
        return 
$product;
    }
}

if( !
function_exists("parse_csv") ){
    function 
parse_csv($string){
        global 
$cfg;
       
$data = array();
        if( 
is_string($string) && ( stripos($string"\n") !== FALSE )    ){
           
$data explode("\n"parse_csv_aux($string) );
            foreach(
$data as $key => $row){
               
$columns = array();
               
//$row = strtr(    $row, array( "\";\"" => "\";\"", ";" => " ; " )    );
               
if( stripos($row" ~ ") !== FALSE ){
                   
$columns explode" ~ "$row );
                    if( !
is_array($columns) )$columns = array( strval($columns) );
                   
$data[$key] = $columns;
                }
            }
            return 
$data;
        }
        else if( 
is_string($string) && ( stripos( ($string parse_csv_aux($string)), " ~ ") !== FALSE )    ){
           
$columns explode" ~ "$string );
            if( !
is_array($columns) )$columns = array( strval($columns) );
            return array(
$columns);
        }
        else return 
strval($string);
    } 
/* end function parse_csv */
/* end not function exists parse_csv */

if( !function_exists("store_csv_aux") ){
    function 
store_csv_aux$string ){
        global 
$cfg;
       
$string strtr$string, array( "\n" => "" ) );
       
$product "";
       
$in_quote FALSE;
        for( 
$i $i strlen($string) ; $i++ ){
            if( 
$string{$i} == $cfg[csvEnc] ){
                if(
$in_quote){
                   
$product .= "\"{$cfg[csvEnc]}";
                }
                else{
                   
$product .= "\"\"{$cfg[csvEnc]}";
                   
$in_quote TRUE;
                }
            }
            else if( 
$string{$i} == "," ){
                if(
$in_quote){
                   
$product .= ",";
                }
                else{
                   
$product .= "\",";
                   
$in_quote TRUE;
                }
            }
            else{
                if(
$in_quote){
                   
$product .= $cfg[csvEnc];
                   
$in_quote FALSE;
                   
$product .= $string{$i};
                }
                else{
                   
$product .= $string{$i};
                }
            }
        }
        if(
$in_quote)$product .= $cfg[csvEnc];
        return 
$product;
    }
}

if( !
function_exists("store_csv") ){
    function 
store_csv($data){
        global 
$cfg;
        if(!
is_array($data))return strval($data);
       
$passed_rows FALSE;
       
$product "";
        foreach(
$data as $row){
            if( 
$passed_rows )$product .= "\n";
            if( 
is_array($row) ){
               
$columns "";
               
$passed_cols FALSE;
                foreach(
$row as $column){
                    if( 
$passed_cols )$columns .= ",";
                   
$columns .= store_csv_aux$column );
                   
$passed_cols =TRUE;
                }
               
$product .= strval($columns);
            }
            else{
               
$product .= strtrstrval($row), array("\n" => "") );
            }
           
$passed_rows TRUE;
        }
        return 
$product;
    } 
/* end function store_csv */
/* end not function exists store_csv */
?>

[EDIT BY danbrown AT php DOT net: This is a bugfix rewrite of a function originally written by "Alexander Peev".]
2008-10-31 03:00:47
http://php5.kiev.ua/manual/ru/function.substr.html
Here's a simple direct way of extracting the information you need from a string...

Suppose your string is "C:/www/vhosts/example.com/images/image1.jpg" which points to an image. Let's assume you want the part "images/image1.jpg". We have to do the ff:

<?php
$image
="C:/www/vhosts/example.com/images/image1.jpg"

$image=substr($image,strpos($image,'image', (strlen($image)-strpos($image,'image'))));

echo 
$image."<br/>"//will give 'images/image1.jpg'
?>
2009-02-24 09:30:16
http://php5.kiev.ua/manual/ru/function.substr.html
this function return string between two delimiters
i found it very useful to get text between html tags

<?php
function strbet($inputStr$delimeterLeft$delimeterRight$debug=false) {
   
$posLeft=strpos($inputStr$delimeterLeft);
    if ( 
$posLeft===false ) {
        if ( 
$debug ) {
            echo 
"Warning: left delimiter '{$delimeterLeft}' not found";
        }
        return 
false;
    }
   
$posLeft+=strlen($delimeterLeft);
   
$posRight=strpos($inputStr$delimeterRight$posLeft);
    if ( 
$posRight===false ) {
        if ( 
$debug ) {
            echo 
"Warning: right delimiter '{$delimeterRight}' not found";
        }
        return 
false;
    }
    return 
substr($inputStr$posLeft$posRight-$posLeft);
}
?>
2009-03-10 19:08:26
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I created some functions for entity-safe splitting+lengthcounting:

<?php
function strlen_entities($text)
{
   
preg_match_all(
       
'/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.         
       
'(?:&(?!\w;)))s',$text,$textarray);
    return 
count($textarray[0]);

function 
substr_entities($text,$start,$limit=0)
{
   
$return '';
   
preg_match_all(
       
'/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.         
       
'(?:&(?!\w;)))s',$text,$textarray);
   
$textarray $textarray[0];
   
$numchars count($textarray)-1;
    if (
$start>=$numchars)
        return 
false;
    if (
$start<0)
    {
       
$start = ($numchars)+$start+1;
    }
    if (
$start>=0)
    {
        if (
$limit==0)
        {
           
$end=$numchars;
        }
        elseif (
$limit>0)
        {
           
$end $start+($limit-1);
        }
        else
        {
           
$end = ($numchars)+$limit;
        }

        for (
$i=$start;$i<=$end;$i++)
        {
           
$return .= $textarray[$i];
        }
        return 
$return;
    }
}
?>
2009-03-20 21:19:57
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
And as always there is bound to be a bug:

<?php
function strlen_entities($text)
{
   
preg_match_all(
       
'/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.       
       
'(?:&(?!\w;)))s',$text,$textarray);
    return 
count($textarray[0]);

function 
substr_entities($text,$start,$limit=0)
{
   
$return '';
   
preg_match_all(
       
'/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.       
       
'(?:&(?!\w;)))s',$text,$textarray);
   
$textarray $textarray[0];
   
$numchars count($textarray)-1;
    if (
$start>=$numchars)
        return 
false;
    if (
$start<0)
    {
       
$start = ($numchars)+$start+1;
    }
    if (
$start>=0)
    {
        if (
$limit==0)
        {
           
$end=$numchars;
        }
        elseif (
$limit>0)
        {
           
$end $start+($limit-1);
        }
        else
        {
           
$end = ($numchars)+$limit;
        }

        for (
$i=$start;($i<=$end && isset($textarray[$i]));$i++)
        {
           
$return .= $textarray[$i];
        }
        return 
$return;
    }
}
?>
2009-03-21 19:52:40
http://php5.kiev.ua/manual/ru/function.substr.html
Substring utf-8 strings!
very simple!

<?php
function substru($str,$from,$len){
    return 
preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'$from .'}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'$len .'}).*#s','$1'$str);
}
?>
2009-04-08 03:28:14
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
If you need to get the first $num Chars of $str and remove them from $str you'll want to use following function:

<?php
function string_shift(&$str,$num) {
   
$cutOff=substr($str,0,$num);
   
$str=substr($str,$num);
    return 
$cutOff;
}
?>
2009-04-15 10:13:15
http://php5.kiev.ua/manual/ru/function.substr.html
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.

This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.

If you need an empty string instead of a boolean FALSE you should typecast the result to a string.

<?php
$a 
substr('123456'6);              // equivalent to $a = FALSE
$a = (string) substr('123456'6);   // equivalent to $a = '';
?>
2009-04-18 05:07:54
http://php5.kiev.ua/manual/ru/function.substr.html
For getting a substring of UTF-8 characters, I highly recommend mb_substr

<?php
        $utf8string 
"cakeæøå";

        echo 
substr($utf8string,0,5);
       
// output cake#
       
echo mb_substr($utf8string,0,5,'UTF-8');
       
//output cakeæ
?>
2009-04-29 09:25:13
http://php5.kiev.ua/manual/ru/function.substr.html
If you need a word-sensitive and also html-tags aware version of substr, this one should do the job. It works fine for me

<?php
/**
* word-sensitive substring function with html tags awareness
* @param text The text to cut
* @param len The maximum length of the cut string
* @returns string
**/
function substrws$text$len=180 ) {

    if( (
strlen($text) > $len) ) {

       
$whitespaceposition strpos($text," ",$len)-1;

        if( 
$whitespaceposition )
           
$text substr($text0, ($whitespaceposition+1));

       
// close unclosed html tags
       
if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) {

            if( !empty(
$aBuffer[1]) ) {

               
preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);

                if( 
count($aBuffer[1]) != count($aBuffer2[1]) ) {

                    foreach( 
$aBuffer[1] as $index => $tag ) {

                        if( empty(
$aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag)
                           
$text .= '</'.$tag.'>';
                    }
                }
            }
        }
    }

    return 
$text;
}
?>
2009-05-06 04:52:16
http://php5.kiev.ua/manual/ru/function.substr.html
Drop extensions of a file (even from a file location string)

<?php

$filename 
"c:/some dir/abc defg. hi.jklmn";

echo 
substr($filename0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

?>

output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. (^_^)
2009-06-08 02:58:33
http://php5.kiev.ua/manual/ru/function.substr.html
Shortens the filename and its expansion has seen.

<?php
$file 
"Hellothisfilehasmorethan30charactersandthisfayl.exe";

function 
funclongwords($file)
{
if (
strlen($file) > 30)
{
$vartypesf strrchr($file,".");
$vartypesf_len strlen($vartypesf);
$word_l_w substr($file,0,15);
$word_r_w substr($file,-15);
$word_r_a substr($word_r_w,0,-$vartypesf_len);

return 
$word_l_w."...".$word_r_a.$vartypesf;
}
else
return 
$file;
}
// RETURN: Hellothisfileha...andthisfayl.exe
?>
2009-07-26 06:39:52
http://php5.kiev.ua/manual/ru/function.substr.html
Shortens the filename and its expansion has seen.

$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}

// RETURN: Hellothisfileha...andthisfayl.exe
// other simples on rollyz.net
2009-07-26 06:40:14
http://php5.kiev.ua/manual/ru/function.substr.html
Shortens the filename and its expansion has seen.

$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}

// RETURN: Hellothisfileha...andthisfayl.exe
// other simples on rollyz.net
2009-07-26 06:44:41
http://php5.kiev.ua/manual/ru/function.substr.html
One thing to keep in mind when using string indexes and UTF-8 is that string indexes are NOT multi-byte safe.

<?php
$string 
'äää1';
echo 
$string[3];
?>

Outputs:
¤

When it logically should output "1". This is not a bug, as PHP 'normal' string functions are not intended to be multi-byte safe. This can be solved by using this function

<?php
/**
 * 
 * @param string $string String to "search" from
 * @param int $index Index of the letter we want.
 * @return string The letter found on $index.
 */
function charAt($string$index){
    if(
$index mb_strlen($string)){
        return 
mb_substr($string$index1);
    }
    else{
        return -
1;
    }
}
?>
2009-10-05 07:42:19
http://php5.kiev.ua/manual/ru/function.substr.html
<?php

// Substring without losing word meaning and
// tiny words (length 3 by default) are included on the result.
// "..." is added if result do not reach original string length

function _substr($str$length$minword 3)
{
   
$sub '';
   
$len 0;
   
    foreach (
explode(' '$str) as $word)
    {
       
$part = (($sub != '') ? ' ' '') . $word;
       
$sub .= $part;
       
$len += strlen($part);
       
        if (
strlen($word) > $minword && strlen($sub) >= $length)
        {
            break;
        }
    }
   
    return 
$sub . (($len strlen($str)) ? '...' '');
}

?>
2009-10-08 14:52:24
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
<?php
//substring without words breaking

$str "aa bb ccc ddd ee fff gg hhh iii";

echo 
substr(($str=wordwrap($str,$,'$$')),0,strpos($str,'$$'));
?>
2009-11-19 11:46:35
http://php5.kiev.ua/manual/ru/function.substr.html
<?php

//removes string from the end of other

function removeFromEnd($string$stringToRemove) {
   
$stringToRemoveLen strlen($stringToRemove);
   
$stringLen strlen($string);
   
   
$pos $stringLen $stringToRemoveLen;

   
$out substr($string0$pos);

    return 
$out;
}

$string 'picture.jpg.jpg';
$string removeFromEnd($string'.jpg');
?>
2010-01-28 12:32:18
http://php5.kiev.ua/manual/ru/function.substr.html
I've seen numerous requests over the years from people trying to put together templating systems using XML parsers or regular expressions - you can create a simple template system with the following class. It could easily be expanded to take advantage of parameters, conditionals, etc.

<?php

class Template
{
    const 
OPEN_BRACKET "{";
    const 
CLOSE_BRACKET "}";

    public static function 
inject(array $source$template)
    {
       
$ob_size strlen(self::OPEN_BRACKET);
       
$cb_size strlen(self::CLOSE_BRACKET);
       
       
$pos 0;
       
$end strlen($template);
       
        while(
$pos <= $end)
        {
            if(
$pos_1 strpos($templateself::OPEN_BRACKET$pos))
            {
                if(
$pos_1)
                {
                   
$pos_2 strpos($templateself::CLOSE_BRACKET$pos_1);
                   
                    if(
$pos_2)
                    {
                       
$return_length = ($pos_2-$cb_size) - $pos_1;
                       
                       
$var substr($template$pos_1+$ob_size$return_length);
                       
                       
$template str_replace(self::OPEN_BRACKET.$var.self::CLOSE_BRACKET$source[$var], $template);
                       
                       
$pos $pos_2 $cb_size;
                    }
                    else
                    {
                        throw new 
exception("Incorrectly formed template - missing closing bracket. Please check your syntax.");
                        break;
                    }
                }
            }
            else
            {
               
//exit the loop
               
break;
            }
        }
       
        return 
$template;
    }
   
}

//array of values to inject into the template
$array = array("NAME" => "John Doe",
               
"DOB"    => "12/21/1986",
               
"ACL" => "Super Administrator");

//template using '{' and '}' to signify variables 
$template "This is your template, {NAME}. You were born on {DOB} and you are a {ACL} on this system.";

echo 
Template::inject($array$template);
?>
2010-02-01 14:46:04
http://php5.kiev.ua/manual/ru/function.substr.html
It doesn't support Chinese characters under utf-8 so well. 

with utf-8, each Chinese character counts with 3 in length.
with utf-16, each one counts as 2 in length.
2010-03-25 03:39:47
http://php5.kiev.ua/manual/ru/function.substr.html
I had some problems with the order of the closing of tags.

Example: 
<p>some <b><i>very</i>long</b> text to show my problem</p>
would be converted to (if the script would cut the part after "very":
<p>some <b><i>very</p></b></i>

My second problem was, that the script didn't recognized tags like <a href="#" title="title">

So my version based on bennys and erez' work looks like this:

<?php
function mb_substrws($text$length 180) {
    if((
mb_strlen($text) > $length)) {
       
$whitespaceposition mb_strpos($text' '$length) - 1;
        if(
$whitespaceposition 0) {
           
$chars count_chars(mb_substr($text0, ($whitespaceposition 1)), 1);
            if (
$chars[ord('<')] > $chars[ord('>')]) {
               
$whitespaceposition mb_strpos($text">"$whitespaceposition) - 1;
            }
           
$text mb_substr($text0, ($whitespaceposition 1));
        }
       
// close unclosed html tags
       
if(preg_match_all("|(<([\w]+)[^>]*>)|"$text$aBuffer)) {
            if(!empty(
$aBuffer[1])) {
               
preg_match_all("|</([a-zA-Z]+)>|"$text$aBuffer2);
                if(
count($aBuffer[2]) != count($aBuffer2[1])) {
                   
$closing_tags array_diff($aBuffer[2], $aBuffer2[1]);
                   
$closing_tags array_reverse($closing_tags);
                    foreach(
$closing_tags as $tag) {
                           
$text .= '</'.$tag.'>';
                    }
                }
            }
        }

    }
    return 
$text;
}
?>
2010-04-15 08:50:30
http://php5.kiev.ua/manual/ru/function.substr.html
I noticed a slight issue when parsing out long strings using the substr function. 

Here is my string: $merge = "UPDATE AssistanceRequest SET RequestorID = '4301' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

To parse out the WHERE portion I used: 
$whereClause = substr($merge, strpos($merge,'WHERE', (strlen($merge) - strpos($merge,'WHERE')))); 
Normally the function returned: $whereClause = "WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

This $whereClause gives me the WHERE clause to modify the MSSQL database records being manipulated. So that when I used $whereClause as the WHERE clause to create subsequent SQL, I used the following syntax: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

This should have returned: $setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

As long as the length of the original $merge string was less than 104 characters, the $setDeleteFlag sql came out correctly. However, when the length of the original $merge string exceeded 104 characters, I got this returned:

$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' WHERE RequestorID IN ( '4535','6222','4865','5137','4893')"

The result was that the bIsDirty field for every record in the database was set to 'DELETE'. I fixed it by breaking apart the substr to create the original $whereClause so that it looked like this:

$wherePosition = strpos($merge,'WHERE');
$whereClause = substr($merge, $wherePosition, strlen($merge) - $wherePosition);
$setDeleteFlag = "UPDATE AssistanceRequestor SET bIsDirty = 'DELETE' " . $whereClause;

I do have to note that I run PHP 5.x on my development server, while I think the production host is still on 4.x. I did not seem to have an issue in development, but I don't think I tested strings longer than 104 characters. Maybe this issue has been corrected in version 5.x.
2010-07-19 20:00:55
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
Find differences between wokr of substr function when string length less then -start
ex:
$id=4;
var_dump(substr($id, -3));
at PHP Version 5.2.12 at windows it outputs: string(1) "4"
but at PHP Version 5.2.4-2ubuntu5.10: bool(false)
2010-09-23 05:20:08
http://php5.kiev.ua/manual/ru/function.substr.html
Using substr() to examine characters of a string without altering the string.

<?php
$string 
'This is my string';
$length strlen($string);
$myChar 'm';

for(
$i 0$i $length$i++) {

   
$showString_i substr($string$i1);
    if(
$myChar == $showString_i) return $i;
}
?>

can also examine subs.
2010-10-09 15:58:35
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
Simple UTF-8 Multibyte solution (without mb_substr)

<?php
  $string
="texto en español";
  echo 
substr($string,0,14); //Outputs: texto en espa�
?>

<?php
  $string
="texto en español";
  echo 
utf8_encode(substr(utf8_decode($string),0,14)); //Outputs: texto en españ
?>
2010-10-18 05:23:46
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

<?php
function right($string,$chars)
{
   
$vright substr($stringstrlen($string)-$chars,$chars);
    return 
$vright;
   
}

    echo 
right('0r0j4152',4);
?>

Result: 
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there. 

regards,
2010-10-29 17:10:32
http://php5.kiev.ua/manual/ru/function.substr.html
If you want to have a string BETWEEN two strings, just use this function:

<?php
function get_between($input$start$end)
{
 
$substr substr($inputstrlen($start)+strpos($input$start), (strlen($input) - strpos($input$end))*(-1));
  return 
$substr;
}

//Example:

$string "123456789";
$a "12";
$b "9";

echo 
get_between($string$a$b);

//Output:
//345678
?>
2011-01-14 10:56:45
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
substr is case sensitive.  To make it case-insensitive, use something like:

<?php
if (substr($text,0,6)==strtoupper($find_me))
{
echo 
"Case insensitive $find_me detected.";
}
?>
2011-02-25 08:56:33
http://php5.kiev.ua/manual/ru/function.substr.html
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string.  The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input$slice) {
   
$arg explode(':'$slice);
   
$start intval($arg[0]);
    if (
$start 0) {
       
$start += strlen($input);
    }
    if (
count($arg) === 1) {
        return 
substr($input$start1);
    }
    if (
trim($arg[1]) === '') {
        return 
substr($input$start);
    }
   
$end intval($arg[1]);
    if (
$end 0) {
       
$end += strlen($input);
    }
    return 
substr($input$start$end $start);
}

print 
py_slice('abcdefg''2') . "\n";
print 
py_slice('abcdefg''2:4') . "\n";
print 
py_slice('abcdefg''2:') . "\n";
print 
py_slice('abcdefg'':4') . "\n";
print 
py_slice('abcdefg'':-3') . "\n";
print 
py_slice('abcdefg''-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be  counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg
2011-03-28 16:47:37
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
If you need to parse utf-8 strings char by char, try this one:

<?php
     $utf8marker
=chr(128);
     
$count=0;
     while(isset(
$string{$count})){
       if(
$string{$count}>=$utf8marker) {
         
$parsechar=substr($string,$count,2);
         
$count+=2;
       } else {
         
$parsechar=$string{$count};
         
$count++;
       }
       
/* do what you like with parsechar ... , eg.:*/  echo $parsechar."<BR>\r\n";
     }
?>

- it works without mb_substr
- it is fast, because it grabs characters based on indexes  when possible and avoids any count and split functions
2011-05-06 07:17:07
http://php5.kiev.ua/manual/ru/function.substr.html
Автор:
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.

Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
2011-07-08 04:07:19
http://php5.kiev.ua/manual/ru/function.substr.html
<?php

//Here is the function created for strip tags with sub string 

function displaySubStringWithStrip($string$length=NULL)
{
    if (
$length == NULL)
           
$length 50;
   
   
$stringDisplay substr(strip_tags($string), 0$length);
    if (
strlen(strip_tags($string)) > $length)
       
$stringDisplay .= ' ...';
    return 
$stringDisplay;
}

?>
2011-11-23 04:30:39
http://php5.kiev.ua/manual/ru/function.substr.html
Here is a recursion function to get parts of passed string which are in a char. Func looks pretty, and works fast, tell me please if you find more opt way.
<?php
$s 
"info= &make&,endvcc &new& &another&info";
echo 
str_cut($s,"&",",");
//output:
//make,new,another

function str_cut($s,$a,$d="")
{
   
$f=strpos($s,$a)+1;
   
$l=strpos($s,$a,$f);
   
$outsubstr($s,$f,$l-$f);
                if 
    (
strpos($s,$a,$l+1)!==false)
    {
$s=substr($s,$l+1);$out.=$d.str_cut($s,$a,$d);}
return 
$out;
}
?>

it is possible to output in array, you have to returns a var as an array.
Also you can add an extra needle, which would be compare with the end of strings :
replace to 
$l=strpos($s,$b,$f)-$f;
and dont forget to pass into recursion call $b value, but i did like that 
$b=func_get_arg(func_num_args()-1);
care! the last argument should be $a, because $b getting last arg. like that:
function str_cut($s,$d="",$a)
but i think this method of getting $b not the best way for perfomance.
Sorry for my English.
2012-01-27 18:43:13
http://php5.kiev.ua/manual/ru/function.substr.html

    Поддержать сайт на родительском проекте КГБ