Home > Net >  How get first two only word from string and replace whitespace by underscore (_)
How get first two only word from string and replace whitespace by underscore (_)

Time:03-23

here is the case, I had a string variable contains a fullname with title. I wanna get the name only, without the coma and the title. Then I replace the white space result with underscore (_).

what I've tried :

$name = 'John Doe, Ph.D'
$get_name = preg_split('/[\s,] /', $name, 2);
$username = strtolower($get_name[0] . '_' . $get_name[1]);

dd($get_name, $username); //result : john_doe, ph.d

How to get the result like : john_doe from the variable $name ?

CodePudding user response:

You could use preg_replace to first replace remove everything after the second name (if present) to the end and then replace white-space with _ , passing the lower-cased input to it. This allows you to support input such as 'Fred , M.Sc' and 'Fred John Doe , B.A' as well:

$name = 'John Doe, Ph.D';
$get_name = preg_replace(array('/^([a-z] (?:\s [a-z] )?)[^a-z].*$/', '/\s /'), array('$1', '_'), strtolower($name));
echo $get_name;
$name = 'Fred , M.Sc';
$get_name = preg_replace(array('/^([a-z] (?:\s [a-z] )?)[^a-z].*$/', '/\s /'), array('$1', '_'), strtolower($name));
echo $get_name;
$name = 'Fred John Doe , B.A';
$get_name = preg_replace(array('/^([a-z] (?:\s [a-z] )?)[^a-z].*$/', '/\s /'), array('$1', '_'), strtolower($name));
echo $get_name;

Output:

john_doe
fred
fred_john

Demo on 3v4l.org

  • Related