Função PHP substr_replace()
Exemplo
Substitua "Olá" por "mundo":
<?php
echo substr_replace("Hello","world",0);
?>
Definição e uso
A função substr_replace() substitui uma parte de uma string por outra string.
Nota: Se o parâmetro inicial for um número negativo e o comprimento for menor ou igual ao inicial, o comprimento se tornará 0.
Nota: Esta função é segura para binários.
Sintaxe
substr_replace(string,replacement,start,length)
Valores de parâmetro
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
replacement | Required. Specifies the string to insert |
start | Required. Specifies where to start replacing in the string
|
length | Optional. Specifies how many characters should be replaced. Default is the same length as the string.
|
Detalhes técnicos
Valor de retorno: | Retorna a string substituída. Se a string for uma matriz, a matriz será retornada |
---|---|
Versão do PHP: | 4+ |
Registro de alterações: | A partir do PHP 4.3.3, todos os parâmetros agora aceitam arrays |
Mais exemplos
Exemplo
Comece substituindo na 6ª posição na string (substitua "world" por "earth"):
<?php
echo substr_replace("Hello world","earth",6);
?>
Exemplo
Comece substituindo na 5ª posição a partir do final da string (substitua "world" por "earth"):
<?php
echo substr_replace("Hello world","earth",-5);
?>
Exemplo
Insira "Hello" no início de "world":
<?php
echo substr_replace("world","Hello ",0,0);
?>
Exemplo
Substitua várias strings de uma só vez. Substitua "AAA" em cada string por "BBB":
<?php
$replace = array("1: AAA","2: AAA","3: AAA");
echo implode("<br>",substr_replace($replace,'BBB',3,3));
?>
❮ Referência de String PHP