Função PHP substr()
Exemplo
Retorne "mundo" da string:
<?php
echo substr("Hello world",6);
?>
Definição e uso
A função substr() retorna uma parte de uma string.
Sintaxe
substr(string,start,length)
Valores de parâmetro
Parameter | Description |
---|---|
string | Required. Specifies the string to return a part of |
start | Required. Specifies where to start in the string
|
length | Optional. Specifies the length of the returned string. Default is to the end of the string.
|
Detalhes técnicos
Valor de retorno: | Retorna a parte extraída de uma string, ou FALSE em caso de falha, ou uma string vazia |
---|---|
Versão do PHP: | 4+ |
Registro de alterações: | PHP 7.0 - Se string = start (em caracteres), retornará uma string vazia. Versões anteriores retornam FALSE. PHP 5.2.2 - 5.2.6 - Se start tem a posição de truncamento negativo, FALSE é retornado. Outras versões obtêm a string desde o início. |
Mais exemplos
Exemplo
Usando o parâmetro start com diferentes números positivos e negativos:
<?php
echo substr("Hello world",10)."<br>";
echo substr("Hello world",1)."<br>";
echo substr("Hello world",3)."<br>";
echo substr("Hello world",7)."<br>";
echo substr("Hello world",-1)."<br>";
echo substr("Hello world",-10)."<br>";
echo substr("Hello world",-8)."<br>";
echo substr("Hello world",-4)."<br>";
?>
Exemplo
Usando os parâmetros start e length com diferentes números positivos e negativos:
<?php
echo substr("Hello world",0,10)."<br>";
echo substr("Hello world",1,8)."<br>";
echo substr("Hello world",0,5)."<br>";
echo substr("Hello world",6,6)."<br>";
echo substr("Hello world",0,-1)."<br>";
echo substr("Hello world",-10,-2)."<br>";
echo substr("Hello world",0,-6)."<br>";
?>
❮ Referência de String PHP