Show only names in the same variable
P粉899950720
P粉899950720 2023-09-05 09:41:43
0
2
635
<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粉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