Drop extensions of a file (even from a file location string)
<?php
$filename = "c:/some dir/abc defg. hi.jklmn";
echo substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));
?>
output: c:/some dir/abc defg. hi
Hope it may help somebody like me.. (^_^)
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 .
If string is less than or equal to start characters long, FALSE will be returned.
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 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
?>
See Also
- strrchr() - Find the last occurrence of a character in a string
- substr_replace() - Replace text within a portion of a string
- preg_match() - Perform a regular expression match
- trim() - Strip whitespace (or other characters) from the beginning and end of a string
- mb_substr() - Get part of string
- wordwrap() - Wraps a string to a given number of characters
substr
08-Jun-2009 06:58
06-May-2009 08:52
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 > 0 )
$text = substr($text, 0, ($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;
}
?>
29-Apr-2009 01:25
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æ
?>
18-Apr-2009 09:07
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 = '';
?>
15-Apr-2009 02:13
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;
}
?>
08-Apr-2009 07:28
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);
}
?>
22-Mar-2009 01:52
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;
}
}
?>
21-Mar-2009 03:19
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;
}
}
?>
11-Mar-2009 01:08
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);
}
?>
24-Feb-2009 03:30
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'
?>
31-Oct-2008 09:00
<?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 = 0 ; $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 = 0 ; $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 .= strtr( strval($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".]
31-Oct-2008 12:52
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($wdata, 0, $op);
$ndata=substr($wdata, $op, strlen($wdata)-$op);
$cp=strpos($ndata, "\n");
$link=substr($ndata, 0, $cp);
$oc=$op+$cp;
$wdata=substr($wdata, $oc, strlen($wdata)-$oc);
$edata=$edata."$rdata <a href=\"$link\">more info</a><br />";
}
return $edata;
}
?>
24-Oct-2008 09:31
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 !'; }
?>
29-Sep-2008 05:01
Simple use of substr to determine possession:
<?php
function possessive ($word) {
return $word.(substr($word, -1) == 's' ? "'" : "'s");
}
// Davis => Davis'
// Paul => Paul's
?>
19-Sep-2008 10:21
<?php
function insert_substr($str, $pos, $substr) {
$part1 = substr($str, 0, -$pos);
$part2 = substr($str, -$pos);
return $part1.$substr.$part2;
}
?>
29-Aug-2008 07:57
***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
05-Aug-2008 02: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 ;)
31-Jul-2008 09: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'], '/');
?>
29-Jul-2008 06:18
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;
}
?>
27-Jun-2008 08: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.
<?php
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 10:13
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($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
return $string;
}
?>
17-Mar-2008 11: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!
01-Mar-2008 01: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 01: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.
<?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.
?>
06-Jan-2008 04: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;
}
?>
24-Sep-2007 05: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;
}
}
?>
12-Sep-2007 11: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 10: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[