Ignore the last characters of a string in PHP

1

Good morning, I'm doing the INSERT in a table of the database in two fields, one that is the username and another is the password.

At the moment both fields have the same content, for example

USER | PASSWORD [email protected] [email protected]

This is because I am sending the same parameter for both fields.

I would like to ignore the user name from @ mail.com so that the name will remain only in the mail.

I understand that this is achieved with the substr function I am not aware of how the part of the string I want to delete could be ignored.

I hope you can help me, regards.

    
asked by Guillermo Ricardo Spindola Bri 12.03.2018 в 20:23
source

4 answers

8

You can try this:

<?php
$email = explode("@","[email protected]"); 
echo $email[0]; // Imprime "nombre"
echo $email[1]; // Imprime "correo.com" 
?>

I hope it's the answer you're looking for.

    
answered by 12.03.2018 / 20:27
source
2

There are several ways to do this:

Using strstr 1

$email="[email protected]";
$user = strstr($email, '@', true); // Para el usuario, a partir de PHP 5.3.0
$domain = strstr($email, '@'); //Para el dominio

Using substr

$email="[email protected]";
$user = substr($email, 0, strpos($email, '@'));

Using explode

$email="[email protected]";
$partes = explode("@", $email);
$user = $partes[0];

You can also use REGex, but it is not worth using this method for something so simple.

1 The true parameter, with which the user name would be obtained, is compatible only with PHP versions higher than version 5.3.0 .

    
answered by 12.03.2018 в 20:36
1

It's relatively simple friend the only thing you have to do is how you say to use substr and it's like this.

echo substr('abcdef', 0, 8); //Devuelve 'abcdef'

In this code, as you can see, you can take a certain part of the text string as shown, but in your case it would not work because you need to return everything before the @ symbol, so you would use something like the following.

NOTE: You can use the substr but I think it is a bit more elegant the way I propose below.

before ('@', '[email protected]'); //Devuelve biohazard

before ($this, $inthat) { 
    return substr($inthat, 0, strpos($inthat, $this)); 
};

In this case, you will return everything that is before the symbol that you indicate and I think that is what you are looking for. I hope you find it useful.

    
answered by 12.03.2018 в 20:35
0

I could solve it this way

$usuario = '[email protected]';

$pos = strpos($usuario, '@'); //Busca el indice donde está la arroba

if ($pos === false) {
    echo "No se encontró la @";
} else {
    $usuarioSinCorreo=substr($usuario, 0, $pos-1 ); //Substrae desde el inicio de la cadena hasta la posición donde se encuentra la arroba
    echo $usuarioSinCorreo;
}
    
answered by 12.03.2018 в 20:34