Show only names in the same variable
P粉899950720
P粉899950720 2023-09-05 09:41:43
0
2
477

I have a variable in PHP:

userInfo->name;?>

This will output their first and last name (i.e. Joe Bloggs)

I only want to display the first character of their first and last name (i.e. Joe B)

I can show the first character of their name and hide the rest by doing the following in CSS:

p { visibility: hidden; } p::first-letter { visibility: visible; }

I thought I could use a function in PHP, something like this:

function abbreviateName($this->userInfo->name) { if($this->userInfo->name == "") return ""; $tmp = explode(" ", $this->userInfo->name, 2) if(count($tmp)<=1) { return ucwords($tmp[0])."."; } else { $fn = ucwords($tmp[0]); $ln = ucwords(substr($tmp[1],0,1); return $fn.". ".$ln."."; } }

But it doesn’t work

P粉899950720
P粉899950720

reply all (2)
P粉642920522

Assuming there is always a space, you can index from the beginning of the string to a substring after the space.

substr($this->userInfo->name, 0, strpos($this->userInfo->name, " ") + 2);
    P粉680487967

    Okay, so I came up with a nice and simple solution:

    [$first_name, $last_name] = explode(' ', $this->userInfo->name); echo $first_name . " " . substr($last_name, 0, 1);

    Looks like it works great!

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!