Funções de String PHP

A string is a sequence of characters, such as "Hello world!"

Funções de String PHP

In this section, we will learn about commonly used string manipulation functions.

PHP strlen() function

The strlen() function returns the length of a string, in characters.

The following example returns the length of the string "Hello world!":

Exemplo

<?php
echo strlen("Hello world!");
?>

Executar Exemplo

The output of the above code is: 12

Dica:The strlen() function is commonly used in loops and other functions, and it is important to determine when a string ends. (For example, in a loop, we may need to stop the loop after the last character of the string).

Counting words in a string

The PHP str_word_count() function counts words in a string:

Exemplo

<?php
echo str_word_count("Hello world!"); // Output 2
?>

Executar Exemplo

A saída do código acima é:

2

Inverter string

A função strrev() do PHP inverte a string:

Exemplo

<?php
echo strrev("Hello world!"); // Saída !dlrow olleH
?>

Executar Exemplo

A saída do código acima é:

!dlrow olleH

Função strpos() PHP

A função strpos() é usada para pesquisar um caractere ou texto específico dentro de uma string.

Se encontrar uma correspondência, retornará a posição do primeiro caractere correspondente. Se não encontrar correspondência, retornará FALSE.

No exemplo a seguir, é pesquisado o texto "world" na string "Hello world!":

Exemplo

<?php
echo strpos("Hello world!","world");
?>

Executar Exemplo

A saída do código acima é: 6.

Dica:Na exemplo acima, a posição da string "world" é 6. A razão pela qual é 6 (e não 7) é porque a posição do primeiro caractere da string é 0, não 1.

Substituir texto na string

A função str_replace() do PHP substitui uma string por outra dentro de uma string.

O exemplo a seguir substitui "Kitty" pelo texto "world":

Exemplo

<?php
echo str_replace("world", "Kitty", "Hello world!"); // Saída Hello Kitty!
?>

Executar Exemplo

A saída do código acima é:

Hello Kitty!

Manual de Referência Completo String PHP

Para acessar o manual de referência completo das funções de string, acesse nosso Manual de Referência String PHP.

Este manual fornece uma descrição breve e exemplos de cada função!