Cut Name substr ()

1

I have the following names saved with last name + name in a database GONZALEZ PEREZ JUAN GABRIEL in a report I just want to show the names of them. For Juan, it would be like that

JUAN GABRIEL How could you do it using substr() ?

    
asked by MoteCL 31.08.2018 в 17:47
source

2 answers

2

If you want to do it with substr() for this specific case, it would be like this:

$nombre = substr('GONZALEZ PEREZ JUAN GABRIEL', 16, 12);

But the numbers would change for each name. Maybe it's better in your case with explode like this:

$nombres = explode(" ", "GONZALEX PEREZ JUAN GABRIEL");
$nombre = $nombres[2] . " " . $nombres[3];

Of course this only works if you have two surnames and two names. If the names do not follow that format, you would have to add more logic.

    
answered by 31.08.2018 / 17:55
source
5

By reading this comment of yours :

  

In the DB I keep the names and surnames in a pure variable GONZALEZ PEREZ JUAN GABRIEL in this way.

I must say that the solution to this question is one: urgently redesign your data model. The error is that, because you can not use a single column to save everything together with the name and surname .

The difficulty you are having now to want to separate both data is the result of not having separated them when designing the database. It is impossible to create an algorithm or function that differentiates your first and last name in such a design, because:

  • It is impossible to know how many words have all the names and surnames that are going to be stored in the database.
  • because there are names that seem surnames and surnames that look like names
  • because it is impossible to know where the name ends and the last name begins
  • because ...
  • because ...

Later there will be other complications ... I want to see the face you are going to put when asked for a list organized by the first surname, or by the second surname ... OMG !!! And the table has 10 million records! How can I normalize it now? How will I know in data like this where the name ends and the surname begins: José Martín Pérez and José Martín Pérez ... it turns out that in the first one your name is José Martín , but in the second your name is José and their last names are Martín Perez ... Normalizing when there are several thousand records is going to be complicated.

Or when they ask you for a list with surnames that begin with the letter B ... Or anything else that may be necessary in the future.

Solution

Redesign the data to normalize it , creating one or two columns for the name, and one or two columns for the surnames, as the case may be.

  • nombre
  • primer_apellido
  • segundo_apellido --optional
answered by 31.08.2018 в 18:08