***Caution newbie***
To extract a file Extension this fuction could be useful.
$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
substr
(PHP 4, PHP 5)
substr — Return part of a string
Description
Returns the portion of string specified by the start and length parameters.
Parameters
- string
-
The input string.
- start
-
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.
If start is negative, the returned string will start at the start 'th character from the end of string .
Example #1 Using a negative start
<?php
$rest = substr("abcdef", -1); // returns "f"
$rest = substr("abcdef", -2); // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?> - length
-
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 #2 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"
?>
Return Values
Returns the extracted part of string.
Examples
Example #3 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 achieved using "square brackets"
$string = 'abcdef';
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string)-1]; // f
?>
substr
29-Aug-2008 02:57
19-Aug-2008 10:33
The documentation no longer states what happens when length is omitted. It should state that in this case, the function returns whatever would have been returned if a length equal to the remaining length of the source string was supplied.
05-Aug-2008 09:59
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 ;)
01-Aug-2008 04:17
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($string, 0, strrpos($string, $needle)+1);
}
$current_dir = substrtruncate($_SERVER['SCRIPT_NAME'], '/');
?>
30-Jul-2008 01:18
I wrote this simple function
<?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;
}
?>
28-Jun-2008 03:09
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.
function cutText($string, $setlength) {
$length = $setlength;
if($length<strlen($string)){
while (($string{$length} != " ") AND ($length > 0)) {
$length--;
}
if ($length == 0) return substr($string, 0, $setlength);
else return substr($string, 0, $length);
}else return $string;
}
03-Jun-2008 05:13
easy and quick way to limit length of a text by not cutting full words:
textLimit('some words', 7) is 'some...'
function textLimit($string, $length, $replacer = '...')
{
if(strlen($string) > $length)
return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
return $string;
}
17-May-2008 12:54
In response to: "dev at arthurk dot com"
Your code:
<?php
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, -1 * strripos($filename, '.'));
?>
The second line don't work.
This code work fine:
<?php
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, strripos($filename, '.'));
?>
Example:
$filename="anything.jpg"
strripos($filename, '.'); -> position 8
substr($filename, -1 * 8); -> "hing.jpg" (-8 chars from end)
But:
substr($filename, 8); -> ".jpg" (starts in the char number 8)
Sorry for my english, and, "dev at arthurk dot com", sorry, i don't disturb you, only want contribute.
Open Source is revolution!!! -;)
02-Apr-2008 01:34
Here is a quick and easy way to get the base name and the extension of a file. It also handles filenames like foo-1.0.1.tar (where foo-1.0.1 is the base, and .tar is the extension).
<?php
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, -1 * strripos($filename, '.'));
?>
Notice the use of "strripos()" instead of "stripos()".
If you need to detect .tar.gz, etc. as the ext (starting at the first dot), substitute "stripos" for "strripos".
26-Mar-2008 08:14
ben at enemy dot dk
10-Feb-2008 05:48
The function he wrote to cut text whithout cutting in middle of words, doesn't work if $lenght is smaller than $string size..
Just add a simple test and it works perfect for listing texts with a maximum chars:
function cutText($string, $length) {
if($length<strlen($string)){
while ($string{$length} != " ") {
$length--;
}
return substr($string, 0, $length);
}else return $string;
}
17-Mar-2008 06:53
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($inString, 0, $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!
10-Mar-2008 12:59
kriskra's charAt script has the nifty feature that when $pos == -1, it will give the last letter of the string.
I am not sure (did not test), but I believe this code might be slightly faster:
<?php
/**
* Function to get a single character from a string
*
* @param string $str String to get char from
* @param integer $pos Get char from this position of $str. Should be zero or greater
* @return mixed Integer -1 when $pos is out of range, otherwise the charater at position $pos.
*/
function charAt($str, $pos) {
return ($pos < 0 || $pos >= strlen($str)) ? -1 : $str{$pos};
}
?>
Please note that this version does NOT have this nifty feature.
When $pos == -1, result will be -1.
01-Mar-2008 08:21
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;
}
?>
23-Feb-2008 08:12
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.
<?
$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.
?>
10-Feb-2008 11:48
Needed a method to cut text without cutting in middle of words, so made this little function to iterate back until a whitespace is found, and then cut the text from there.
function cutText($string, $length) {
while ($string{$length} != " ") {
$length--;
}
return substr($string, 0, $length);
}
06-Jan-2008 11:47
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($string, 0, $length);
$pos_end = strrpos($pre_string, " ");
if($pos_end === false) $string = $pre_string."...";
else $string = substr($pre_string, 0, $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;
}
?>
11-Oct-2007 05:03
Just want to note that if you are retrieving sub-strings of length zero, this function breaks in the base case (the source being an empty string):
substr('123',0,0) returns string(0) ""
substr('12',0,0) returns string(0) ""
substr('1',0,0) returns string(0) ""
but
substr('',0,0) returns bool(false)
Although this is the documented behavior, I would consider it unexpected in many circumstances.
25-Sep-2007 12:55
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($str, 0, $limit - 3) . '...';
}
else
{
return $str;
}
}
?>
13-Sep-2007 06:06
I prefer
<?php
function short_name($str, $limit)
{
return strlen($str) > $limit ? substr($str, 0, $limit - 3) . '...' : $str;
}
?>
Now, every returned string has a maximum length of $limit chars (instead of $limit + 3).
31-Aug-2007 05:56
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.
31-Jul-2007 05:06
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.
27-Jun-2007 04:40
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
26-Jun-2007 05:31
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.
10-May-2007 11:08
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
?>
07-Mar-2007 04:51
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);
}
?>
28-Feb-2007 10:10
If you need to extract information in a string between delimeters then you can use this:
Inputstring is:
"Heidi Klum Supermodel" <info@HeidiKlum.com>
Here the script
<?php
$emailadresse = "\"Heidi Klum Supermodel\" <info@HeidiKlum.com>";
$outputvalue = extractBetweenDelimeters($emailadresse,"\"","\"");
echo $outputvalue; // shows Heidi Klum Supermodel
echo "<br>";
$outputvalue = extractBetweenDelimeters($emailadresse,"<",">");
echo $outputvalue; // shows info@HeidiKlum.com
function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
$posLeft = stripos($inputstr,$delimeterLeft)+1;
$posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
return substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
14-Feb-2007 05:20
/*
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"));
*/
13-Feb-2007 10:45
Here is also a nice (but a bit slow) alternative for colorizing an true color image:
// $colorize = hexadecimal code in String format, f.e. "10ffa2"
// $im = the image that have to be computed
$red = hexdec(substr($colorize, 0, 2));
$green = hexdec(substr($colorize, 2, 2));
$blue = hexdec(substr($colorize, 4, 2));
$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<<8 | $b;
}
$pal[$lum_c] = $red<<16 | $green<<8 | $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<<8 | $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]);
}
}
19-Oct-2006 05:19
<?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($start, 1);
$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($start, 1);
}
$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($end, 1);
$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($end, 1);
}
$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($str, 0, $end);
}
?>
16-Oct-2006 07:47
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($str, 0, $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-1 && ($thisLen+strlen($body[$i+1])) < $maxlen+$maxoverflow?true:false);
$i++;
} while ($cycle);
return $output.$elli;
}
else return $str;
}
?>
16-Aug-2006 11:31
<?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($handle, filesize($filename));
fclose($handle);
$contents = htmlspecialchars($contents);
$title = substring_between($contents,'<title>','</title>');
?>
18-Mar-2006 04:17
It might be obvious to some but I took some time to figure it out that you can't call
<?php
$text = substr($text, 0, -0);
?>
and expect $text to be unchanged.
A bit of context might make the issue clearer. I'm calculating how many characters I need to chop of the end of the string and them I call substr as
<?php
$text = substr($text, 0, -$charactersToChop);
?>
Sometimes $charactersToChop is set to 0 and in this case I wanted $text to be unchanged. The problem is that in this case $text gets set to an empty string.
Why? Because -0 is the same as 0 and substr($text, 0, 0) obviously returns an empty string.
In case someone want a fix:
<?php
if ($charactersToChop) {
$text = substr($text, 0, -$charactersToChop);
}
?>
That's it.
13-Feb-2006 08:21
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.
04-Feb-2006 09:37
Here's a function I wrote that'll insert a string into another string with an offset.
// $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($intostring, 0, $offset);
$part2 = substr($intostring, $offset);
$part1 = $part1 . $insertstring;
$whole = $part1 . $part2;
return $whole;
}
11-Jan-2006 04:34
Add on to "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.
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, $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++;
}
if ($Start == 'right') $Result = strrev($Result);
return $Result;
}
05-Jan-2006 10:22
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
14-Dec-2005 05:54
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 