substring - PHP : how separate a string into 4 parts?

Solution:

use explode the split strings

https://www.php.net/manual/en/function.explode.php

1.

you could say split string by [white-space] but in this case you would get

$return_array = explode(" ", "Bill Gates - Founder and CEO - Microsoft");
["Bill", "Gates", "-", "Founder", "and", "CEO", "-", "Microsoft"]

2.

if you say split by [white-space dash white-space] you would get

$return_array = explode(" - ", "Bill Gates - Founder and CEO - Microsoft");
["Bill Gates", "Founder and CEO", "Microsoft"]

Answer

Solution:

If, for the name part, you assume there will always be at least two words, you can make a pretty naive regular expression to get it in one go:

$str = 'Bill Gates - Founder and CEO - Microsoft';
preg_match('/^(.+) (.+) - (.+) - (.+)$/', $str, $parts);

print_r($parts);

/*
Array
(
    [0] => Bill Gates - Founder and CEO - Microsoft
    [1] => Bill
    [2] => Gates
    [3] => Founder and CEO
    [4] => Microsoft
)
*/

Or using named groups if you don't want to use array indices 1 through 4:

$str = 'Bill Gates - Founder and CEO - Microsoft';
preg_match('/^(?P<firstName>.+) (?P<lastName>.+) - (?P<position>.+) - (?P<company>.+)$/', $str, $parts);

print_r($parts);

/*
Array
(
    [firstName] => Bill
    [lastName] => Gates
    [position] => Founder and CEO
    [company] => Microsoft

// but also:
    [0] => Bill Gates - Founder and CEO - Microsoft
    [1] => Bill
    [2] => Gates
    [3] => Founder and CEO
    [4] => Microsoft
)
*/

Answer

Solution:

To complete uVolpus answer:

The 'explode' is the best solution in this case, however it is important to double explode the array in order to get the first and last names.

Here is the full code:

   $str = 'Bill Gates - Founder and CEO - Microsoft';
   $array = explode(" - ", $str);
   $new_array = array();
   $new_array['full_name'] =  $full_name = $array[0];
   $new_array['first_name'] = $first_name = explode(' ',$array[0])[0];
   $new_array['last_name'] = $last_name = explode(' ',$array[0])[1];;
   $new_array['position'] = $position = $array[1];
   $new_array['company'] = $company = $array[2];

   echo "new_array"; print_r($new_array);

Source