Printing a String until a space is found


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?

asked by anonymous 11.11.2015 / 20:04

8 answers


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);



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];
11.11.2015 / 20:08

Example :

$nome_completo = "Ciclano Fulano";
$palavras = explode(" ", $nome_completo);
$primeiro_nome = $palavras[0];


Result :


11.11.2015 / 20:08

Another way:

$str = 'John Doe';

echo substr($str, 0, strpos($str.' ', ' '));
11.11.2015 / 21:10

It can be as follows:

$string = "Nome Completo";
$string = explode(" ", $string);
echo $string[0];

In this case, only "name" will appear

11.11.2015 / 20:08

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

11.11.2015 / 20:08

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é
11.11.2015 / 20:12

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:


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]
11.12.2015 / 16:01

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:


// 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 );
08.12.2015 / 13:47