I get a String through an input and I insert it into the database. When I list, I want only the first name of the person, that is, until the first space is found. Is there a function that does this?
I get a String through an input and I insert it into the database. When I list, I want only the first name of the person, that is, until the first space is found. Is there a function that does this?
You can use the strstr () function because it retries only the first part of that string. By default the value returned is to the right of the limiter. To change this is to get the value on the left report true
in the third argument ( $befero_needle
)
$str = "João da Silva Sauro";
echo strstr($str, ' ', true);
Output:
João
About the explode () none of the replies commented that from php5.4 it is possible to return the desired index already in the function call.
$str = "João da Silva Sauro";
echo explode(' ', $str)[0];
Example :
$nome_completo = "Ciclano Fulano";
$palavras = explode(" ", $nome_completo);
$primeiro_nome = $palavras[0];
print_r($primeiro_nome);
Result :
Cyclane
Another way:
$str = 'John Doe';
echo substr($str, 0, strpos($str.' ', ' '));
It can be as follows:
$string = "Nome Completo";
$string = explode(" ", $string);
echo $string[0];
In this case, only "name" will appear
Yes, just use this example:
// aqui é o campo caminho que vai retornar da consulta.
$caminho ="Faturamento Cupom";
echo "Caminho a ser quebrado<br>".$caminho;
$string = explode(' ', $caminho);
echo "vou imprimir só a primeira parte do caminho ".$string[0];
to print the last part link
One of many ways is this
$nome = 'João da Silva';
echo preg_replace("#^([^\s]*)\s.*?$#", "$1", $nome); // Exibe João
$nome = 'José';
echo preg_replace("#^([^\s]*)\s.*?$#", "$1", $nome); // Exibe José
Then she might get hurt: '(
They forgot to mention the (not so known) function strtok
.
See there:
$nome = 'Wallace de Souza Vizerra';
echo strtok($nome, ' ')
The output will be:
"Wallace"
Another example is that in versions higher than PHP 5.4, you no longer need to assign a variable to explode
, and then print the 0
index.
Just do:
$nome = "wallace de souza";
echo explode(' ', $nome)[0]
First wipe the blanks on the left.
Then, if it is a user entry, it can enter "other characters that are not spaces", such as the invisible character, an ENTER, or a TAB. Or it may be that it only spells the first name, so using simple PHP functions will fail. Use regular expression. Here is the code:
<?php // Sua string $str = ' Márcio jalber'; // Limpa espaços em branco $strLimpa = ltrim( $str, " \t\n" ); // Limpa a string $strFinal = preg_replace( '/(.*?)[\n\t\s].*/', '', $strLimpa );