connoisseurs!

Such a question - there is a record in the base of such a format "xxxx Ivan Ivanovich" - you need to pull out the name, the problem is that in some cases the record is of such a format "Ivan Ivan Ivanovich", i.e. no number at first, please tell me the universal solution of the problem

  • What could be xxxx instead? Anything? - Octavian

6 answers 6

If you only need a name, you can merge the last name with the initial characters and, if anything, paint the name already the second regular or substring, like this:

$re = '/^(.+)\s+(\S+)\s+(\S+)$/m'; $str = 'хххх Иванов Иван Иванович Иванов Иван Иванович'; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); // Print the entire match result var_dump($matches); 
  • Thank you for what you need! - The Enotik Patascun
  • @SyntaxWEB 6stPROD WowSuite, you can still try my version - Node_pro
 '/^.*?\h+\K[А-Яа-я]+(?=\h+[А-Яа-я]+$)/m' 

See the regular expression demo

    If there are only numbers (or nothing) before the full name, you can cut them off with a single line of code:

     $str = '123 Иванов Иван Иванович'; echo preg_replace('~(?:\d+\h)?(?=(?:\pL+\h*)+)~u', '', $str); 

    Result:

     Иванов Иван Иванович 

    Watch the demo

      Find the index of the first letter in uppercase and with it to make substr

       $a = "123443 Вася"; $upperIndex = -1; for(int $i = 0; $i < strlen($a); $i++) { if(ctype_upper($a[$i])) { $upperIndex = i; break; } } if( $upperIndex != -1 ) { $userName = substr($a, $upperIndex); } 
      • I am not familiar with regulars, could you help me? - The Enotik Patascun

      Alternatively, the desired result can be obtained using the sql query. I'm not sure that this option will be the most productive, but this option

       SELECT REGEXP_REPLACE(`name`, '^[^ ]+', '') as name FROM `table` WHERE `name` REGEXP '[^ ]+ Иванов Иван Иванович' 

      Replace "name" and "table" with your own. By the way, if you say that instead of xxxx maybe, specify a regular expression. For example, if 4 digits:

       SELECT REGEXP_REPLACE(`name`, '^[0-9]{4}', '') as name FROM `table` WHERE `name` REGEXP '[0-9]{4} Иванов Иван Иванович' 

        You can simply print the last but one word.

         echo reset( array_slice( explode(" ", $str), -2, 1)); 

        Or more universal option

         $str = '123 Иванов Иван Иванович'; $str=preg_replace('/[^А-Яа-я \-]/ui', '', $str); # убераем всё кроме букв, пробелов, тире $fio=explode(' ',trim($str)); # получаем массив [Ф,И,O] echo $fio[1]; # выводим имя