Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 16
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
W takich dniach, jak ten, nie żałuję, że wykupiłem abonament. Korzystam z porad na tych stronach nawet kilkanaście razy w tygodniu i dzięki nim prace nad stronami dla klientów idą mi o wiele szybciej, a strony wyglądają bardziej profesjonalnie. Nie wiem, jak mogłem wcześniej pracować bez dostępu do porad w tym serwisie!

Wojciech Miszkiewicz

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

substr

(PHP 3, PHP 4, PHP 5)

substr -- Return part of a string

Description

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

substr() returns the portion of string specified by the start and length parameters.

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.

Przykład 1. 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 achived using "curly braces"
$string = 'abcdef';
echo
$string{0};                // a
echo $string{3};                // d
echo $string{strlen($string)-1}; // f

?>

If start is negative, the returned string will start at the start'th character from the end of string.

Przykład 2. Using a negative start

<?php
$rest
= substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

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.

Przykład 3. 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"
?>

See also strrchr(), substr_replace(), ereg(), trim(), mb_substr() and wordwrap().




User Contributed Notes

Matt Mangels
15-Jan-2006 08: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 10: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
05-Jan-2006 04: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 11: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 < strlen($posttext) - 1) {
              
$next_char = substr($posttext,$i + 1,1);
           }
           else {
              
$next_char = "";
           }
          
// First check if quotes are on
          
if (!$quotes_on) {
              
// Check if it's a tag
               // On a "<" add 3 if it's an opening tag (like <a href...)
               // or add only 1 if it's an ending tag (like </a>)
              
if ($current_char == '<') {
                   if (
$next_char == '/') {
                      
$tag_counter += 1;
                   }
                   else {
                      
$tag_counter += 3;
                   }
               }
              
// Slash signifies an ending (like </a> or ... />)
               // substract 2
              
if ($current_char == '/' && $tag_counter <> 0) $tag_counter -= 2;
              
// On a ">" substract 1
              
if ($current_char == '>') $tag_counter -= 1;
              
// If quotes are encountered, start ignoring the tags
               // (for directory slashes)
              
if ($current_char == '"') $quotes_on = TRUE;
           }
           else {
              
// IF quotes are encountered again, turn it back off
              
if ($current_char == '"') $quotes_on = FALSE;
           }
          
          
// Count only the chars outside html tags
          
if($tag_counter == 2 || $tag_counter == 0){
              
$c++;
           }         
                          
          
// Check if the counter has reached the minimum length yet,
           // then wait for the tag_counter to become 0, and chop the string there
          
if ($c > $minimum_length - $length_offset && $tag_counter == 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 01: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
28-Nov-2005 12: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 04:47

<?php
function utf8_substr($str,$from,$len){
# utf8 substr
# www.yeap.lv
 
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 11:10

Truncates a string at a certain position without

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt