|
 |
substr (PHP 3, PHP 4, PHP 5) substr -- Возвращает подстроку Описаниеstring substr ( string string, int start [, int length] )
substr() возвращает подстроку строки
string длиной length,
начинающегося с start символа по счету.
Если start неотрицателен, возвращаемая
подстрока начинается в позиции start от начала
строки, считая от нуля. Например, в строке
'abcdef', в позиции 0 находится
символ 'a', в позиции 2 -
символ 'c', и т.д.
Пример 1. Пример использования substr()
<?php
$rest = substr("abcdef", 1); $rest = substr("abcdef", 1, 3); $rest = substr("abcdef", 0, 4); $rest = substr("abcdef", 0, 8); $string = 'abcdef';
echo $string{0}; echo $string{3}; ?>
|
|
Если start отрицательный, возвращаемая
подстрока начинается с start символа с конца
строки string.
Пример 2. Использование отрицательного start
<?php
$rest = substr("abcdef", -1); $rest = substr("abcdef", -2); $rest = substr("abcdef", -3, 1); ?>
|
|
Если length положительный, возвращаемая строка
будет не длиннее length символов.
Если длина строки string меньше или равна
start символов, возвращается FALSE.
Если length отрицательный, то будет отброшено
указанное этим аргументом число символов с конца строки
string. Если при этом позиция начала
подстроки, определяемая аргументом start,
находится в отброшенной части строки, возвращается пустая строка.
Пример 3. Использование отрицательного length
<?php
$rest = substr("abcdef", 0, -1); $rest = substr("abcdef", 2, -1); $rest = substr("abcdef", 4, -4); $rest = substr("abcdef", -3, -1); ?>
|
|
См. также описание функций
strrchr(),
substr_replace(),
ereg(),
trim() и
mb_substr().
substr
kontakt at hundeinfos dot de
18-Jul-2006 01:27
With your Script, i had a problem in a "while" statement.
So i wrote this function. It works very well, without Problems:
/**
* Findet das letzte Leerzeichen und gibt den String bis
* dahin zurück
*/
function hsSubstr($pvString,$pvMaxLaenge) {
$text = substr($pvString,0, $pvMaxLaenge);
$posLetzesLeerzeichen = strrpos($text, " ");
$rueckgabe = substr($text, 0, $posLetzesLeerzeichen);
if (strlen($pvString) > $pvMaxLaenge)
{
$rueckgabe .= " ...";
}
return $rueckgabe;
}
elvijs
14-Jul-2006 10:55
drifterlrsc, I like your idea, but this simple code makes my home server crash (Win32, Apache 2.0.58, PHP 5.1.4). It happens when the string is shorter than $n. So I changed the code to work right. Here is how it looks now:
<?php
function shorten($s,$n) {
if (strlen($s)<$n) {
exit;
}
$scan=0;
while($scan==0){
if(substr($s,$n,1)==' '){
$scan=1;
}else{
$n++;
}
}
echo substr($s,0,$n) . "...";
}
?>
Code below prevents function execution if the string is shorter than $n.
if (strlen($s)<$n) {
exit;
}
Excuse me for my bad English.
rodrigo at fabricadeideias dot com
17-Mar-2006 01: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.
SpikeDaCruz
16-Mar-2006 07:45
If you want to substring the middle of a string with another and keep the words intact:
<?php
function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
$strlen = strlen($string);
if ($strlen <= $max)
return $string;
$lengthtokeep = $max - strlen($rep);
$start = 0;
$end = 0;
if (($lengthtokeep % 2) == 0) {
$start = $lengthtokeep / 2;
$end = $start;
} else {
$start = intval($lengthtokeep / 2);
$end = $start + 1;
}
$i = $start;
$tmp_string = $string;
while ($i < $strlen) {
if ($tmp_string[$i] == ' ') {
$tmp_string = substr($tmp_string, 0, $i) . $rep;
$return = $tmp_string;
}
$i++;
}
$i = $end;
$tmp_string = strrev ($string);
while ($i < $strlen) {
if ($tmp_string[$i] == ' ') {
$tmp_string = substr($tmp_string, 0, $i);
$return .= strrev ($tmp_string);
}
$i++;
}
return $return;
return substr($string, 0, $start) . $rep . substr($string, - $end);
}
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30) . "\n";
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30, '...') . "\n";
?>
x11 at arturaz dot afraid dot org
17-Feb-2006 05:01
/**
* Cut string to n symbols and add delim but do not break words.
*
* Example:
* <code>
* $string = 'this is some content to be shortened';
* echo myfragment($string, 15);
* </code>
*
* Output: 'this is some content...'
*
* @access public
* @param string string we are operating with
* @param integer character count to cut to
* @param string|NULL delimiter. Default: '...'
* @return string processed string
**/
function myfragment($str, $n, $delim='...') { // {{{
$len = strlen($str);
if ($len > $n) {
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
} // }}}
shadzar
13-Feb-2006 05: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
$filename = "counter_file.txt";
$pathtoiamges = "http://www.yoursite.com/counter/";$extension = ".gif";$counter=file_get_contents($filename);
$counter++;
$count=$counter;
$current=0;
$visit=array("");while (strlen($count)>0)
{
$current++;
$visit[$current]=substr($count,0,1);$count=substr($count,1,strlen($count));}
foreach ($visit as $vis)
{
if ($vis!=""){echo "<img src=\"". $pathtoimages . $vis . .$extension . "\">";}
}
$list = fopen($filename, "w+");
fwrite($list, $counter);
fclose($list);
?>
requires a file to store the counter and 10 images to represent the digits (0-9) if used as a counter.
wishie at gmail dot com
03-Feb-2006 06: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;
}
Matt Mangels
14-Jan-2006 11:39
To felipe, wouldn't the following be easier (assuming you even wanted a charAt function in the first place, because you can use $string{$number}):
<?php
function charAt($string, $num) {
return $string{$num};
|
?>
Bradley from California
10-Jan-2006 01: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;
}
eallik at hotmail dot com
04-Jan-2006 07: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
mr at bbp dot biz
14-Dec-2005 02: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) {
$tag_counter = 0;
$quotes_on = FALSE;
if (strlen($posttext) > $minimum_length) {
$c = 0;
for ($i = 0; $i < strlen($posttext); $i++) {
$current_char = substr($posttext,$i,1);
if ($i < strlen($posttext) - 1) {
$next_char = substr($posttext,$i + 1,1);
}
else {
$next_char = "";
}
if (!$quotes_on) {
if ($current_char == '<') {
if ($next_char == '/') {
$tag_counter += 1;
}
else {
$tag_counter += 3;
}
}
if ($current_char == '/' && $tag_counter <> 0) $tag_counter -= 2;
if ($current_char == '>') $tag_counter -= 1;
if ($current_char == '"') $quotes_on = TRUE;
}
else {
if ($current_char == '"') $quotes_on = FALSE;
}
if($tag_counter == 2 || $tag_counter == 0){
$c++;
}
if ($c > $minimum_length - $length_offset && $tag_counter == 0 && ($next_char == ' ' || $cut_words == TRUE)) {
$posttext = substr($posttext,0,$i + 1);
if($dots){
$posttext .= '...';
}
return $posttext;
}
}
}
return $posttext;
}
?>
felipe at spdata dot com dot br
29-Nov-2005 04:48
JavaScript charAt PHP equivalent
<?php
function charAt($str, $pos)
{
return (substr($str, $pos, 1)) ? substr($str, $pos, 1) : -1;
}
?>
If found, return the charecter at the specified position, otherwise return -1
drifterlrsc at yahoo dot com
27-Nov-2005 03:37
another function simular to Jays
function myfragment($s,$n) {
$scan=0;
while($scan==0){
if(substr($s,$n,1)==' '){
$scan=1;
}else{
$n++;
}
}
return substr($s,0,$n) . "...";
}
$string='this is some content to be shortened';
echo myfragment($string,15);
will output
this is some content...
goes to the first space after 15 characters.
18-Oct-2005 07:47
<?php
function utf8_substr($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);
}
?>
bob at 808medien dot de
16-Sep-2005 02:10
Truncates a string at a certain position without cutting words into senseless pieces.
I hope this is usefull for some of you and that it is not another redundant note (I didn't find one) ...
<?php
$string = "Truncates a string at a certain position without »cutting« words into senseless pieces.";
$maxlength = 75;
$extension = " ...";
function truncate_string ($string, $maxlength, $extension) {
$cutmarker = "**cut_here**";
if (strlen($string) > $maxlength) {
$string = wordwrap($string, $maxlength, $cutmarker);
$string = explode($cutmarker, $string);
$string = $string[0] . $extension;
}
return $string;
}
echo truncate_string ($string, $maxlength, $extension);
?>
Best
Bob
andrzej dot martynowicz at gmail dot com
03-Sep-2005 02:19
substr() can provide easy way to get a filename with or without extension
<?
function getFilename( $file, $extension = true ) {
return ($extension || false === $dot = strrpos( basename( $file ), '.' ))
? basename( $file ) : substr( basename( $file ), 0, $dot );
}
echo getFilename( 'foo.php' ); echo getFilename( 'foo.php', false ); echo getFilename( 'dir/foo.php' ); echo getFilename( 'foo' ); echo getFilename( '.php', false ); ?>
concordia at jusgoo dot farvista dot net
18-Aug-2005 12:30
You can use PHP substr() along with MySQL to make mailstrings.
<?php
require ('../mysql_connt.php'); $mail_string = NULL; $query = 'SELECT email FROM users'; $result = mysql_query ($query); if ($result) { while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
$mail_string .= '<a href="mailto:' . $row[0] . '">' . $row[0] . '</a>, '; }
echo substr ($mail_string, 0, -2); }
?>
This will create a mailstring like this:
email1@domain.com, email2@domain.com, email3@domain1.com
frank at jkelloggs dot dk
25-Jul-2005 02:37
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));
}
}
?>
jeroen at jscwebdesign dot nl
09-Jul-2005 02:58
javazz at gmail dot com:
Would it be much easier if instead of
<?php
while (substr ($path, -1) != '/'){
$path = substr( $path, 0, -1);
}
?>
you used
<?php
$path = substr($path, strrpos($path, '/') + 1, strlen($path));
?>
julius at infoguiden dot no
04-Jul-2005 11:23
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.
function str_stop($string, $max_length){
if (strlen($string) > $max_length){
$string = substr($string, 0, $max_length);
$pos = strrpos($string, " ");
if($pos === false) {
return substr($string, 0, $max_length)."...";
}
return substr($string, 0, $pos)."...";
}else{
return $string;
}
}
php_net at thomas dot trella dot de
29-Jun-2005 08:07
I needed to cut a string after x chars at a html converted utf-8 text (for example Japanese text like 嬰謰弰脰欰罏).
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($str, 0, $start);
if (strlen($str) > $start)
$rVal .= " ...";
return $rVal;
}
?>
javazz at gmail dot com
15-Jun-2005 10:04
A really simple script to shorten the web site's address (http://something.com/file.php -> http://something.com/)
in case you need to know where you are without showing the .php file.
<?php
$path = "http://" . $_SERVER['HTTP_HOST'] . $HTTP_SERVER_VARS["SCRIPT_NAME"];
$path_php = path;
while (substr ($path, -1) != '/'){
$path = substr( $path, 0, -1);
}
echo $path_php."<br>";
echo $path;
?>
jay
15-Jun-2005 03:34
Better written version of my function below.
<?php
function elliStr($s,$n) {
for ( $x = 0; $x < strlen($s); $x++ ) {
$o = ($n+$x >= strlen($s) ? $s : ($s{$n+$x} == " " ? substr($s,0,$n+$x) . "..." : ""));
if ( $o != "" ) { return $o; }
}
}
print(elliStr("have a nice day", 7)); print(elliStr("have a nice day", 6)); ?>
ivanhoe011 at gmail dot com
07-Jun-2005 08:31
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:
<?php
echo substr($my_string, 2, 1);
echo $my_string{2};
?>
curly braces syntax is faster and more readable IMHO..
rob NOSPAM at clancentric dot net
07-Jun-2005 03:43
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.
<?
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).'...';
}
}
?>
pedro at leb dot usp dot br
06-Jun-2005 11:22
watch out, in dead dot screamer at seznam dot cz's script: if your $end is larger than $length, you may have strange results...
Nice function if it is for your own use, though (eg. not allowing the user to change the $end)
jay
05-Jun-2005 11:26
A more sophisticated ellipse function that lets you end only at the end of words instead of breaking a word to print an ellipse, can however change it using the switch at the end (1/0). This could probably be written better, my PHP skills aren't amazing yet like some others :p
<?php
function elliStr($s,$n,$e) {
if ( isset($e) ) {
if ( $e == 1 ) {
if ( substr(substr($s, 0, $n), -1, 0) != " " ) {
for ( $x = 0; $x <= strlen($s); $x++ ) {
if ( substr($s, strlen(substr($s, 0, $n))+$x-1, 1) == " " ) {
$newendval = $x;
$stop = 1;
} else {
print(substr(substr($s, 0, $n), strlen(substr($s, 0, $n)), $x));
}
if ( isset($stop) ) {
return substr($s, 0, $n+$x-1) . "...";
}
}
} else {
return substr($s, 0, $n) . "...";
}
} else {
if (strlen($s) > $n) {
return substr($s, 0, $n) . "...";
} else {
return $s;
}
}
} else {
return false;
}
}
?>
Hope this helps.
dead dot screamer at seznam dot cz
02-Jun-2005 10:29
This is a little better ellipsis function
<?
function betterEllipsis($string, $length, $end='...')
{
return (strLen($string)>$length)?subStr($string,0,$length-strLen($end)).$end:
$string;
}
?>
webmaster at jpriestley dot org
29-May-2005 05:24
A quick function to return a string with appended ellipsis if over a specified length:
function ellipsis($string, $length) {
return (strlen($string) > $length) ? substr($string, 0, $length) . '...' : $string;
}
print ellipsis('foobar', 3) returns 'foo...'
michiel at mb-it dot nl
29-May-2005 01:01
For the stripos() function is only available for PHP 5 the checkword() function might be a useful alternative in PHP 3 or 4.
eviloverlord at gmail dot com
27-May-2005 06:57
It appears the "checkword" function below is just a (poor) implementation of stripos. Stripos will find the (case-insensitive) location of a string in another string, returning FALSE if it is not found.
michiel at mb-it dot nl
26-May-2005 01:19
Loads of spam messages in a guestbook I created forced me to create a new boolean-function using the substr in order to check for unwanted words in posted messages. Take for instance the bad word is "poker":
function checkword($string,$word)
{
$count = 0;
for($i=0;$i<=strlen($string);$i++)
{
if (strtolower(substr($string,$i,strlen($word))) == strtolower($word))
{
$count++;
}
}
if ($count>0)
{
return true;
}
else
{
return false;
}
}
$badword = "poker";
if (!checkword($mytext,$badword))
{
addtoguestbook();
}
bleakwind at msn dot com
25-May-2005 10:15
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
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;
}
$str = "123456ֽ123456ַ123456ȡ";
for($i=0;$i<30;$i++){
echo "<br>".bite_str($str,$i,20);
}
?>
bleakwind at msn dot com
25-May-2005 10:11
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
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;
}
$str = "123456ֽ123456ַ123456ȡ";
for($i=0;$i<30;$i++){
echo "<br>".bite_str($str,$i,20);
}
?>
ben
23-May-2005 08:59
two useful functions that I use and make life a tad easier:
<?php
function left($string, $length) {
return substr($string, 0, $length);
}
function right($string, $length) {
return substr($string, -$length, $length);
}
?>
fanfatal at fanfatal dot pl
17-May-2005 03:38
Sorry for my misteake in previous function - can u change this line:
<?php
$pattern = str_replace(chr(1),'(.*?)',preg_quote($clean));
$pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
?>
I will be glad ;]
fanfatal at fanfatal dot pl
16-May-2005 11:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags
<?php
function csubstr($string, $start, $length=false) {
$pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
$clean = preg_replace($pattern, chr(1), $string);
if(!$length)
$str = substr($clean, $start);
else {
$str = substr($clean, $start, $length);
$str = substr($clean, $start, $length + substr_count($str, chr(1)));
}
$pattern = str_replace(chr(1),'(.*?)',preg_quote($clean));
if(preg_match('/'.$pattern.'/is', $string, $matched))
return $matched[0];
return $string;
}
?>
Using this is similar to simple substr.
Greatings ;]
...
matt at spcan dot com
03-May-2005 11:47
substr($lbar_html,0,-2); // does not work
and
substr($lbar_html, 0, -2); // works as expected
do not work the same.
woutermb at gmail dot com
21-Mar-2005 11:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.
<?php
function text($string,$limit=20,$chop=10){
$text = explode(" ",$string);
while(list($key, $value) = each($text)){
$length = strlen($value);
if($length >=20){
for($i=0;$i<=$length;$i+=10){
$new .= substr($value, $i, 10);
$new .= " ";
}
$post .= $new;
}
elseif($length <=15){
$post .= $value;
}
$post .= " ";
}
return($post);
}
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);
echo($output); ?>
I hope it was useful.. :)
vampired64 at gmail dot com
14-Mar-2005 01:28
an easy way to return a file size to 1 decimal place and MB
<?
$size = filesize("filename.jpg"); $size = $size/1024; $pos = strpos(".",$size); $size = substr($size,0,$pos+3); ?>
steve at unicycle dot co dot nz
13-Mar-2005 09:34
To quickly trim an optional trailing slash off the end of a path name:
if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );
cody at apparitiondesigns dot com
10-Mar-2005 01:02
I don't know if I didn't realize this because I'm not very smart - or if i just over looked it, but the string needs to be a string. Not an integer.
ex.
<?php
$var = 12345;
echo $var{0}; $var = '12345';
echo $var{0}; ?>
Matias from Argentina
24-Feb-2005 12:55
Hello,
Here you are a function to format your
numeric strings. Enjoy it.
<?php
function str_format_number($String, $Format){
if ($Format == '') return $String;
if ($String == '') return $String;
$Result = '';
$FormatPos = 0;
$StringPos = 0;
While ((strlen($Format) - 1) >= $FormatPos){
if (is_numeric(substr($Format, $FormatPos, 1))){
$Result .= substr($String, $StringPos, 1);
$StringPos++;
} Else {
$Result .= substr($Format, $FormatPos, 1);
}
$FormatPos++;
}
return $Result;
}
$String = "541143165500";
$Format = "+00 00 0000.000";
Echo str_format_number($String, $Format); $String = "541143165500";
$Format = "+00 00 0000.0000000";
Echo str_format_number($String, $Format); $String = "541143165500";
$Format = "+00 00 0000.000 a";
Echo str_format_number($String, $Format); ?>
How it works explanation:
str_format_number($String, $Format)
Spects two parameters $String and $Format,
both should be strings.
$String: coulbe any kind of data type,
but it's oriented to numeric string, like
phone numbers.
$Format: should be a conjunction between
numbers (any one) and others caracters.
str_format_number takes each caracter
of $Format, if it isn't a number stores
it to be returned later, but if it is a
number takes the caracter of $String
placed in the position corresponding to
the amount of numbers in $Format so far
starting from zero.
If $Format has less numbers than $string
caracters the rest of the caracters at
the end of $String should be ignored.
If $Format has more numbers than $string
caracters the no caracter will be used,
so those will be ignored.
crashmanATgreenbomberDOTcom
21-Feb-2005 06:34
A fellow coder pointed out to me that $string{-n} will no longer return the character at postion -n is. Use $string{strlen($string) - n) instead.
andrewmclagan at gmail dot com
20-Feb-2005 01:58
Hi there here is a little function i wrote to limit the number of lines in a string, i could not find anything else like it out there
function lineLimiter ($string = "", $max_lines = 1) {
$string = ereg_replace("\n", "##", $string);
$totalLines = (substr_count($string, '##') + 1);
$string = strrev($string);
$stringLength = strlen($string);
while ($totalLines > $max_lines) {
$pos = 0;
$pos = strpos ( $string, "##") + 2;
//$pos = $pos - $stringLength;
$string = substr($string, $pos);
$totalLines--;
}
$string = strrev($string);
$string = ereg_replace("##", "\n", $string);
return $string;
}
Robert
13-Feb-2005 08:36
It is also good to use substr() to get a file extension when manipulating with files. For example:
<?php
$dir = "/full/path/to/folder";
if(is_dir($dir))
{
if($dh = opendir($dir))
{
while(($file = readdir($dh)) !== false)
{
if(substr($file,strlen($file)-4,4) == ".txt")
{
echo "Filename: $file<br/>\n";
}
}
closedir($dh);
}
else
{
echo "Cannot open directory";
}
}
else
{
echo "Cannot open directory";
}
?>
Hopefully this helps
mancini at nextcode dot org
05-Feb-2005 03:10
here are two functions to shrink a string to specified lenght , normally (stri...) or reversed (...ing)
<?php
function limitch($value,$lenght){
if (strlen($value) >= $lenght ){
$limited = substr($value,0,$lenght);
$limited .= "...";
}
return $limited;
}
function limitchrev($value,$lenght){
if (strlen($value) >= $lenght ){
$start = strlen($value)- $lenght;
$limited = "...";
$limited .= substr($value,$start,$lenght);
}
return $limited;
}
?>
vitalic#pisem.net
15-Dec-2004 03:26
Split $string after each $pos, by $space
Example: <?php spaceStr('1836254','-',3); ?>
Would return '183-625-4';
<?php
function spaceStr($string,$space,$pos)
{
$cpos=$pos;
while ($cpos<strlen($string))
{
$string=substr($string,0,$cpos).$space.substr($string,$cpos);
$cpos+=strlen($space)+$pos;
};
return $string;
}
?>
kovacsendre at no_spam_thanks_kfhik dot hungary
02-Nov-2004 07:38
Here are the replacement functions for substr() and strlen() I use when support for html entities is required:
<?php
function html_strlen($str) {
$chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
return count($chars);
}
function html_substr($str, $start, $length = NULL) {
if ($length === 0) return ""; if (strpos($str, '&') === false) { if ($length === NULL)
return substr($str, $start);
else
return substr($str, $start, $length);
}
$chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE);
$html_length = count($chars);
if (
($html_length === 0) or
($start >= $html_length) or
(isset($length) and ($length <= -$html_length)) )
return "";
if ($start >= 0) {
$real_start = $chars[$start][1];
} else { $start = max($start,-$html_length);
$real_start = $chars[$html_length+$start][1];
}
if (!isset($length)) return substr($str, $real_start);
else if ($length > 0) { if ($start+$length >= $html_length) { return substr($str, $real_start);
} else { return substr($str, $real_start, $chars[max($start,0)+$length][1] - $real_start);
}
} else { return substr($str, $real_start, $chars[$html_length+$length][1] - $real_start);
}
}
?>
Example:
html_substr("ábla6bla", 1, 4) -> "bla6"
If you happen to find any bugs, please let me know.
Gordon Axmann
29-Aug-2004 11:33
Two very nice and practical functions:
1. Checks if a string ($needle) turns up at the BEGINNING of another string ($hay):
2. Checks if a string ($needle) appears at the END of another string ($hay):
<?php
function isstartstring($hay,$needle,$casesensitive=true) { if (!$casesensitive) {
$needle=strtolower($needle);
$hay=strtolower($hay);
}
return (substr($hay,0,strlen($needle))==$needle);
}
function isendstring($hay,$needle,$casesensitiv=true) { if (!$casesensitive) {
$needle=strtolower($needle);
$hay=strtolower($hay);
}
return (substr($hay,-strlen($needle))==$needle);
}
?>
lmak at NOSPAM dot iti dot gr
17-Aug-2004 11:59
Regarding windix's function to handle UTF-8 strings: one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8 (available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32). This way the function works for other encodings too (like Greek for example).
The modified function would read like this:
<?php
function utf8_substr($str,$start)
{
preg_match_all("/./u", $str, $ar);
if(func_num_args() >= 3) {
$end = func_get_arg(2);
return join("",array_slice($ar[0],$start,$end));
} else {
return join("",array_slice($ar[0],$start));
}
}
?>
squeegee
10-Aug-2004 07:34
php equivalent of Javascript's substring:
<?php
function substring($str,$start,$end){
return substr($str,$start,($end-$start));
}
?>
fox at conskript dot server
10-Aug-2004 04:01
Here's a little bit of code to chop strings (with html tags) around a specified length while making sure no html tags are chopped. It also prevents chopping while a tag is still open.
Note: this will only work in xhtml strict/transitional due to the checking of "/>" tags and the requirement of quotations in every value of a tag. It's also only been tested with the presence of br, img, and a tags, but it should work with the presence of any tag.
<?php
function html_substr($posttext, $minimum_length, $length_offset) {
$minimum_length = 200;
$length_offset = 10;
$tag_counter = 0;
$quotes_on = FALSE;
if (strlen($posttext) > $minimum_length) {
for ($i = 0; $i < strlen($posttext); $i++) {
$current_char = substr($posttext,$i,1);
if ($i < strlen($posttext) - 1) {
$next_char = substr($posttext,$i + 1,1);
}
else {
$next_char = "";
}
if (!$quotes_on) {
if ($current_char == "<") {
if ($next_char == "/") {
$tag_counter++;
}
else {
$tag_counter = $tag_counter + 3;
}
}
if ($current_char == "/") $tag_counter = $tag_counter - 2;
if ($current_char == ">") $tag_counter--;
if ($current_char == "\"") $quotes_on = TRUE;
}
else {
if ($current_char == "\"") $quotes_on = FALSE;
}
if ($i > $minimum_length - $length_offset && $tag_counter == 0) {
$posttext = substr($posttext,0,$i + 1) . "...";
return $posttext;
}
}
}
return $posttext;
}
biohazard at online dot ge
15-May-2004 01:55
may be by following functions will be easyer to extract the
needed sub parts from a string:
after ('@', 'biohazard@online.ge');
returns 'online.ge'
from the first occurrence of '@'
before ('@', 'biohazard@online.ge');
returns 'biohazard'
from the first occurrence of '@'
between ('@', '.', 'biohazard@online.ge');
returns 'online'
from the first occurrence of '@'
after_last ('[', 'sin[90]*cos[180]');
returns '180]'
from the last occurrence of '['
before_last ('[', 'sin[90]*cos[180]');
returns 'sin[90]*cos['
from the last occurrence of '['
between_last ('[', ']', 'sin[90]*cos[180]');
returns '180'
from the last occurrence of '['
<?
function after ($this, $inthat)
{
if (!is_bool(strpos($inthat, $this)))
return substr($inthat, strpos($inthat,$this)+strlen($this));
};
function after_last ($this, $inthat)
{
if (!is_bool(strrevpos($inthat, $this)))
return substr($inthat, strrevpos($inthat, $this)+strlen($this));
};
function before ($this, $inthat)
{
return substr($inthat, 0, strpos($inthat, $this));
};
function before_last ($this, $inthat)
{
return substr($inthat, 0, strrevpos($inthat, $this));
};
function between ($this, $that, $inthat)
{
return before($that, after($this, $inthat));
};
function between_last ($this, $that, $inthat)
{
return after_last($this, before_last($that, $inthat));
};
function strrevpos($instr, $needle)
{
$rev_pos = strpos (strrev($instr), strrev($needle));
if ($rev_pos===false) return false;
else return strlen($instr) - $rev_pos - strlen($needle);
};
?>
phplist at boonedocks dot net
28-Aug-2003 01:39
If 'start' is negative and greater than the length of the string, PHP seems to return the first 'length' characters of the string. For example, substr('test',-10,1) returns 't'.
05-Jul-2003 05:39
If you want to substring the middle of a string with another and keep the words intact:
<?php
function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
$strlen = strlen($string);
if ($strlen <= $max)
return $string;
$lengthtokeep = $max - strlen($rep);
$start = 0;
$end = 0;
if (($lengthtokeep % 2) == 0) {
$start = $lengthtokeep / 2;
$end = $start;
} else {
$start = intval($lengthtokeep / 2);
$end = $start + 1;
}
$i = $start;
$tmp_string = $string;
while ($i < $strlen) {
if ($tmp_string[$i] == ' ') {
$tmp_string = substr($tmp_string, 0, $i) . $rep;
$return = $tmp_string;
}
$i++;
}
$i = $end;
$tmp_string = strrev ($string);
while ($i < $strlen) {
if ($tmp_string[$i] == ' ') {
$tmp_string = substr($tmp_string, 0, $i);
$return .= strrev ($tmp_string);
}
$i++;
}
return $return;
return substr($string, 0, $start) . $rep . substr($string, - $end);
}
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30) . "\n";
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf sadf sad s', 30, '...') . "\n";
?>
| |