Skip to content
Advertisement

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

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 ?

Advertisement

Answer

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]+)?).*$/', '/s+/'), array('$1', '_'), strtolower($name));
echo $get_name;
echo "n";
$name = 'Fred , M.Sc';
$get_name = preg_replace(array('/^([a-z]+(?:s+[a-z]+)?).*$/', '/s+/'), array('$1', '_'), strtolower($name));
echo $get_name;
echo "n";
$name = 'Fred John Doe , B.A';
$get_name = preg_replace(array('/^([a-z]+(?:s+[a-z]+)?).*$/', '/s+/'), array('$1', '_'), strtolower($name));
echo $get_name;
echo "n";
$name = 'John Doe';
$get_name = preg_replace(array('/^([a-z]+(?:s+[a-z]+)?).*$/', '/s+/'), array('$1', '_'), strtolower($name));
echo $get_name;
echo "n";
$name = 'Fred';
$get_name = preg_replace(array('/^([a-z]+(?:s+[a-z]+)?).*$/', '/s+/'), array('$1', '_'), strtolower($name));
echo $get_name;

Output:

john_doe
fred
fred_john
john_doe
fred

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement