How to display only part of a string using PHP/html/java?

时间:2018-10-02 09:05:26

标签: php string

Usernames on my website are all stored in a form like this "steve.jones" or "lisa-ann.smith", and referred to in my code as only $login (string).

Is there any way i can display only the first name on a site, and changing the first letter to capital?

thanks in advance

5 个答案:

答案 0 :(得分:1)

If you would like just the beginning of the word you can use the explode function. See Doc here:http://php.net/manual/en/function.explode.php

$login = "steve.jones";

Explode function breaks up the string at the delimiter you set. In this case it's a full stop. This breaks the string into separate words each available at an index. Returns an array

$names = explode(".", $login);

The first index gets the first part of the string in this case it's steve

echo $name[0]; // steve

ucfirst makes the first letter a capital letter. See Doc here: http://php.net/manual/en/function.ucfirst.php

 echo ucfirst($name[0]); // Steve

To use this in your code, you can store the result in a new variable or re-write to the existing variable. The complete solution will look like:

$login = "steve.jones";
$names = explode(".", $login);
$forename = ucfirst($names[0]); // Steve 

答案 1 :(得分:1)

In PHP, you can use the explode function delimited by ".", and then use the ucfirst function to convert the same to first letter uppercase

<?php
$login = "steve.jones";
$firstname = explode(".", $login);
$firstname[0] = ucfirst($firstname[0]);
echo $firstname[0];
?>

答案 2 :(得分:0)

You can try explode by '.' + ucfirst

答案 3 :(得分:0)

  • [php doc] use strpos() to find the .
  • [php doc] substr() to get string till the position get from the strpos().
  • [php doc] use ucfirst() to make the first letter capital.

答案 4 :(得分:0)

Note:- Try something before ask

Splitting a string by a regular expression

see documentation:- preg_split

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

Change case of the first letter.

see documentation:- ucfirst

string ucfirst ( string $str )

combining them

// Spliting with '-' and '.'
$splited = preg_split('/([\.\-])/',$string);
// Cahnge casing
$firstname = ucfirst($splited[0]);