0

can anyone helping me to showing first name/word on navigation? i've trying this code

<div class="d-sm-none d-lg-inline-block">Welcome, <?php $string = $this->session->userdata('name'); echo $firstCharacter = $string[0]; ?></div></a>

but this code only showing the first character. i mean like if my name george bush then it only get "Welcome, g". i want to showing more like "Welcome, george" without bush. how to do it?

sorry for my bad english and i'm new to php things. and thanks for helping me before

  • 1
    Does this answer your question? [How to get the first word of a sentence in PHP?](https://stackoverflow.com/questions/2476789/how-to-get-the-first-word-of-a-sentence-in-php) – Jeto Nov 29 '20 at 11:06

2 Answers2

0

To get the 1st word, please use explode to separate the words by space into array, then get the 1st element of the array

Please use this:

<?php 

$string = $this->session->userdata('name'); 
$arr = explode(' ',trim($string));
echo $arr[0]; 

?>

So for your case

<div class="d-sm-none d-lg-inline-block"> Welcome, 
<?php $string = $this->session->userdata('name'); 
$arr = explode(' ',trim($string));echo $arr[0];  ?> </div></a>
Ken Lee
  • 6,985
  • 3
  • 10
  • 29
0

You could use regular expressions, like this:

echo preg_replace('/^([^\s]+)\s*.*$/', '$1', $string);

or split it:

echo (explode(' ', $string))[0];

or 'tok' it:

echo strtok($string, " ")

Sven
  • 524
  • 4
  • 10