substr
(PHP 3, PHP 4 )
substr -- Retorna uma parte de uma string
Descrição
string
substr ( string string, int start [, int length])
substr()retorna a parte de string
especificada pelo parâmetro start e
length.
Se start não for negativo, a string retornada iniciará
na posição start em
string, começando em zero. Por exemplo,
na string 'abcdef', o caractere na posição
0 é 'a', o
caractere na posição 2 é
'c', e assim em diante.
Exemplo 1. Uso basico de substr() <?php
$rest = substr("abcdef", 1); // retorna "bcdef"
$rest = substr("abcdef", 1, 3); // retorna "bcd"
$rest = substr("abcdef", 0, 4); // retorna "abcd"
$rest = substr("abcdef", 0, 8); // retorna "abcdef"
// Outra opção é acessar atravéz de chaves
$string = 'abcdef';
echo $string{0}; // retorna a
echo $string{3}; // retorna d
?> |
|
Se start for negativo, a string retornada
irá começar no caractere start
a partir do fim de string.
Exemplo 2. Usando um inicio negativo <?php
$rest = substr("abcdef", -1); // retorna "f"
$rest = substr("abcdef", -2); // retorna "ef"
$rest = substr("abcdef", -3, 1); // retorna "d"
?> |
|
Se length for dado e for positivo,
a string retornada irá conter length caracteres
começando em start (dependendo do tamanho de
string). Se a string é menor do
que start, será retornado FALSE.
Se length for dado e for negativo, então esta quantidade
caracteres serão omitidos do final de string
(após a posicão de inicio ter sido calculada quando
start for negativo). Se
start denota uma posição além da truncagem,
uma string vazia será retornada.
Exemplo 3. Usando um length negativo <?php
$rest = substr("abcdef", 0, -1); // retorna "abcde"
$rest = substr("abcdef", 2, -1); // retorna "cde"
$rest = substr("abcdef", 4, -4); // retorna ""
$rest = substr("abcdef", -3, -1); // retorna "de"
?> |
|
Veja também strrchr() e
ereg().