Search code examples
phpsubstr

how to display middle name as middle initial if middle name have two words


so i created a form which have middle name field and display the middle name as initial.

preg_split("/[\s,_-]+/",$data["s_mname"])

this code works IF the middle name is only one word.. like Snow it will display as S but my problem is if the middle name is 2 words like De Leon, Delos Santos the initial that will be displayed is DL,DS.. but it should display as D... any idea how to do this..

SUBSTR($data["s_mname"],strrchr($data["s_mname"], ' '), 1)

i tried this code but nothing works i just got this from other site..


Solution

  • Use explode() like this:-

    preg_split("/[\s,_-]+/",explode(' ',$data["s_mname"])[0])
    

    Output:- https://eval.in/828658