|
|
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().
Jim
10-Oct-2007 03: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.
www.kigoobe.com
07-Oct-2007 02:10
Checklist for a file upload using ftp_put()
1. Check the form enctype. I used multipart/form-data to upload word, excel or jpegs using ftp_put()
2. Check the permission of your folder. Unless you have PHPSuExec installed, you change permission of the destination folder to 777
3. See the path of your destination, as that's what creates the problem most of the time. Incase we use ftp_put() with basename($fileName); ($fileName is any file name of your choice + the valid extension for the file uploaded) then the files are uploaded to /home/user/ folder.
So, in case you want to upload your files to a sub folder called dynamicDocuments situated at the same level where your index.php file is, you have to use the path as -
$destination_file = 'public_html/dynamicDocuments/'.basename($fileName);
HTH someone. :)
jordancdarwin at googlemail dot com
04-Oct-2007 02:26
function short_name($str, $limit)
{
return (strlen($str) > $limit && <!--(int) --> $limit > 3) ? substr($str, 0, $limit - 3) . '...' : $str;
}
Rather than that awful mess that you added.
morgangalpin att gmail dotty com
24-Sep-2007 10: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)
{
if ($limit < 3)
{
$limit = 3;
}
if (strlen($str) > $limit)
{
return substr($str, 0, $limit - 3) . '...';
}
else
{
return $str;
}
}
?>
corphi
12-Sep-2007 04: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).
jordancdarwin at googlemail dot com
11-Sep-2007 02:36
To shorten and correct lime's function:
<?php
function short_name($str, $limit) {
return strlen($str) > $limit ? substr($str, 0, $limit) . '...' : $str;
}
?>
Heh.
lime at zybez dot net
03-Sep-2007 10:04
To shorten (and correct) ash at atomic-network dot co dot uk's function:
<?php
function short_name($str) {
$limit = 35;
return strlen($str) > $limit ? substr($str, 0, $limit) . '...' : $str;
}
?>
ash at atomic-network dot co dot uk
31-Aug-2007 07:51
I wanted to shorten long words and add '...' so it would turn :
'thisisareallylongnamedfile.jpg'
and it shall appear like 'thisisareally...'
function short_name($str)
{
$limit = 35;
if(strlen($str > $limit))
{ #
# If the name is greater than 35 characters
# then only display 35 charatcers followed
# by ...
#
return substr($str, 0, $limit) . " ...";
}
else
{ #
# Too small; so no need to change
#
return $str;
}
}
Petez
31-Aug-2007 03: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
beginTimer();
for ($i = 0; $i < 1500000; $i++){
$opening = substr($string,0,11);
if ($opening == 'Lorem ipsum'){
true;
}else{
false;
}
}
$endtime1 = endTimer();
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();
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.
ein at anti-logic dot com
30-Jul-2007 03: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; $fp = fopen("php://memory", 'r+'); fputs($fp, $payload); $total_length=ftell($fp); $payload_chunk = fread ( $fp, $segment_length );
?>
Working with large data sets, mine was 21MB, increased the speed several factors.
lanny at freemail dot hu
26-Jun-2007 03: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.
Jeremy .D
06-Jun-2007 11:48
Reguarding: felipe at spdata dot com dot 29-Nov-2005 10:48
--------------------------------------------------------
JavaScript charAt PHP equivalent
<?php
function charAt($str, $pos)
{
return (substr($str, $pos, 1)) ? substr($str, $pos, 1) : -1;
}
?>
--------------------------------------------------------
There is a bug with the above code, if the charAt(..) is 0 it will return -1, because the conditional returns false.
Code below with minor fix works:
<?php
function charAt($str, $pos)
{
return (strlen(substr($str, $pos, 1))) ? substr($str, $pos, 1) : -1;
}
?>
White-Gandalf
03-Jun-2007 04:42
"substr" seems to be implemented in a sequential way, wasting processing power proportional to the length of the string to be worked on and/or the position of the substring to be extracted.
I found a speed increase by a factor of 1000 for string extraction when the original string has a size of about 1 MB, when i replace "substr" by direct access to the chars at their index.
"Substr" should not be used for extraction of very small pieces.
alias at axew3 dot com
25-May-2007 07:08
Get the page filename for your scripts in a easy simple way:
$pagename = substr(__FILE__, strrpos(__FILE__, "\\") + 1, strlen(__FILE__));
miskotes at yu-corner dot com
20-May-2007 11:15
/*####################################
'A good thing is working with added values like .NET or C#
'Here is a full copy/paste
*/###################################
#
<?php
$filenameToUpper = "Hi_Iam_toto_thomas_etc1_etc2_etc3";
$filenameToUpper = substr($filenameToUpper, 0, 19);
$toFind = "_";
$filenameToUpper = strrev($filenameToUpper); $result = strchr($filenameToUpper, $toFind);
$result = strrev($result); $result = substr($result, 0, -1); echo $result; ?>
#
# End
Antoine
10-May-2007 09: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; echo (int)$x; ?>
rasco at satx dot rr dot com
09-May-2007 02:31
Very nice a dot vanderkolk at gmail dot com, just what I needed.
I have taken your function and added a bit to it, it will strip out ALL the chars after the dot ("."). It would be useful if someone could post how to only strip if they are zeros, and round to 2 chars after the "." if they are not.
// Remove chars after . (200.000 => 200)
function removeDotZero($var)
{
$var = trim($var);
$pos = strpos($var,".");
if($pos != false)
{
$size = strlen($var);
for($i = $size; $i > $pos; $i--)
{
if(substr($var,-1,1) == "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
$var = substr($var,0,($i - 1));
else if(substr($var,-1,1) == ".")
{
$var = substr($var,0,($i - 1));
break;
}
else
break;
}
return $var;
}
else
return $var;
}
/*-------------------*/
// Example
$str = 200.000
$str = removeDotZero($str);
echo $str;
// Output
200
a dot vanderkolk at gmail dot com
29-Mar-2007 01:52
I made a function that removes the last zero's in a string or integer.
<?php
function removeDotZero($var)
{
$var = trim($var);
$pos = strpos($var,".");
if($pos != false)
{
$size = strlen($var);
for($i = $size; $i > $pos; $i--)
{
if(substr($var,-1,1) == "0")
$var = substr($var,0,($i - 1));
else if(substr($var,-1,1) == ".")
{
$var = substr($var,0,($i - 1));
break;
}
else
break;
}
return $var;
}
else
return $var;
}
echo removeDotZero("100.0052520")."\n";
echo removeDotZero("100.0000000")."\n";
?>
// produces:
// 100.005252
// 100
siavashg at gmail dot com
06-Mar-2007 01: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);
}
?>
Jean-Felix, Bern
28-Feb-2007 07: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; echo "<br>";
$outputvalue = extractBetweenDelimeters($emailadresse,"<",">");
echo $outputvalue; function extractBetweenDelimeters($inputstr,$delimeterLeft,$delimeterRight) {
$posLeft = stripos($inputstr,$delimeterLeft)+1;
$posRight = stripos($inputstr,$delimeterRight,$posLeft+1);
return substr($inputstr,$posLeft,$posRight-$posLeft);
}
?>
ijavier aka(not imatech) igjav
14-Feb-2007 02: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"));
*/
persisteus at web dot de
13-Feb-2007 07: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]);
}
}
egingell at sisna dot com
19-Oct-2006 03:19
<?php
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) {
if ($ignore_case === true) {
$strpos = 'stripos'; } else {
$strpos = 'strpos';
}
if ($end === false) {
$end = strlen($str);
}
if (is_string($start)) {
if ($start{0} == '-') {
$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{0} . $start{1} == '\-') {
$start = substr($start, 1);
}
$pos = $strpos($str, $start);
}
$start = $pos !== false ? $pos : 0;
}
$str = substr($str, $start);
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);
}
return substr($str, 0, $end);
}
?>
feedback at realitymedias dot com
15-Oct-2006 05: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;
}
?>
joseph dot morphy at gmail dot com
16-Aug-2006 09:31
<?php
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);
}
}
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = htmlspecialchars($contents);
$title = substring_between($contents,'<title>','</title>');
?>
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.
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;
}
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
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);
}
?>
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));
}
}
?>
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;
}
?>
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).'...';
}
}
?>
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
|
|