skip to Main Content

I have a variable in PHP:

<p><?php echo  $this->userInfo->name;?></p>

This outputs their first name and surname (i.e. Joe Bloggs)

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

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

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

I’m thinking I could use a function in PHP, along the lines of:

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 that’s not working

3

Answers


  1. Chosen as BEST ANSWER

    Ok, so I've come up with a nice and simple solution:

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

    Which seems to do the job nicely!


  2. Assuming there’s always exactly one space, you can take the substring of the string from the start to one after the index of the space.

    substr($this->userInfo->name, 0, strpos($this->userInfo->name, " ") + 2);
    
    Login or Signup to reply.
  3. Couldn’t you just write function in PHP to format the name before it is echo‘d out?

    function regexMatcher($text, $pattern) {
      $__matches = [];
      $__is_match = preg_match($pattern, $text, $__matches);
      return $__is_match ? $__matches : null;
    }
    
    function formatUsername($username) {
      $matches = regexMatcher($username, "/^(w+sw)w*$/");
      echo is_array($matches) ? $matches[1] : $username;
    }
    
    $userInfo = new stdClass();
    $userInfo->name = "Joe Bloggs";
    
    echo formatUsername($userInfo->name); // "Joe B"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search