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 :

JavaScript

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:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

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