search

Home  >  Q&A  >  body text

Show only names in the same variable

<p>I have a variable in PHP: </p> <pre class="brush:php;toolbar:false;"><p><?php echo $this->userInfo->name;?></p></pre> <p>This will output their first and last name (i.e. Joe Bloggs)</p> <p>I only want to display the first character of their first and last name (i.e. Joe B)</p> <p>I can show the first character of their name and hide the rest by doing the following in CSS: </p> <pre class="brush:php;toolbar:false;">p { visibility: hidden; } p::first-letter { visibility: visible; }</pre> <p>I thought I could use a function in PHP, something like this: </p> <pre class="brush:php;toolbar:false;">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."."; } }</pre> <p>But it doesn’t work</p>
P粉899950720P粉899950720452 days ago603

reply all(2)I'll reply

  • P粉642920522

    P粉6429205222023-09-06 00:55:37

    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);
    

    reply
    0
  • P粉680487967

    P粉6804879672023-09-06 00:32:08

    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!

    reply
    0
  • Cancelreply