A note for myself on some code to convert a string of two names into a string made up of the first name and then using the initial of the second name.
copyraw
-- What I have John Smith Fred.Bloggs -- What I want John S. Fred B.
- -- What I have
- John Smith
- Fred.Bloggs
- -- What I want
- John S.
- Fred B.
How?
So different ways, the first thing I did was to create the logic:
copyraw
// default $author_name_disp=$author_name; // check and transform if(strpos($author_name, ' ')!==false){ $author_names=explode(' ', $author_name); $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.'; }elseif(strpos($author_name, '.')!==false){ $author_names=explode('.', $author_name); $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.'; }else{ $author_name_disp=ucfirst($author_name); } // output echo $author_name_disp;
- // default
- $author_name_disp=$author_name;
- // check and transform
- if(strpos($author_name, ' ')!==false){
- $author_names=explode(' ', $author_name);
- $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.';
- }elseif(strpos($author_name, '.')!==false){
- $author_names=explode('.', $author_name);
- $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.';
- }else{
- $author_name_disp=ucfirst($author_name);
- }
- // output
- echo $author_name_disp;
A lot of repetition so lets reduce that a touch:
copyraw
And a little more:
// default $author_name_disp=$author_name; // check and transform $delimiters=array(' ', '.'); foreach($delimiters as $word_index=>$delimiter) { if (strpos($author_name, $delimiter)!==false) { $author_names=explode($delimiters[$word_index], $author_name); $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.'; } } // output echo $author_name_disp;
- // default
- $author_name_disp=$author_name;
- // check and transform
- $delimiters=array(' ', '.');
- foreach($delimiters as $word_index=>$delimiter) {
- if (strpos($author_name, $delimiter)!==false) {
- $author_names=explode($delimiters[$word_index], $author_name);
- $author_name_disp=ucfirst($author_names[0]).' '.strtoupper($author_names[1][0]).'.';
- }
- }
- // output
- echo $author_name_disp;
copyraw
// default $author_name_disp=$author_name; // check and transform foreach(array(' ', '.') as $delimiter) { if (strpos($author_name, $delimiter)!==false) { $author_names=array_map('ucfirst', explode($delimiter, $author_name)); $author_name_disp=$author_names[0].' '.$author_names[1][0].'.'; } } // output echo $author_name_disp;
- // default
- $author_name_disp=$author_name;
- // check and transform
- foreach(array(' ', '.') as $delimiter) {
- if (strpos($author_name, $delimiter)!==false) {
- $author_names=array_map('ucfirst', explode($delimiter, $author_name));
- $author_name_disp=$author_names[0].' '.$author_names[1][0].'.';
- }
- }
- // output
- echo $author_name_disp;
Category: Personal Home Page :: Article: 556
Add comment