compcobalt
compcobalt

Reputation: 1362

Get characters from the left until space then one more character after it

I want to get all of the text from the left and go until there is a space and then get one more character after the space.

example: "Brian Spelling" would be "Brian S"

How can I do this in php?

In ASP the code looks like this:

strName1=left(strName1,InStr(strName1, " ")+1)

Upvotes: 1

Views: 6871

Answers (6)

James L.
James L.

Reputation: 4097

$string = "Brian Spelling";
$element = explode(' ', $string);
$out = $element[0] . ' ' . $element[1]{0};

and just for fun to take Rob Hruska's answer under advisement you could do something like this:

$skip = array( 'jr.', 'jr', 'sr', 'sr.', 'md' );
$string = "Martin Luther King Jr.";
$element = explode(' ', $string);
$count = count( $element );
if( $count > 1)
{
    $out = $element[0] . ' ';
    $out .= ( in_array( strtolower( $element[ $count - 1 ] ), $skip ) )
        ? $element[ $count - 2 ]{0} : $element[ $count - 1 ]{0};
} else $out = $string;
echo $out;

-just edited so "Cher" will work too

Add any suffixes that you want to skip add to the $skip array

Upvotes: 1

Pratik
Pratik

Reputation: 1541

Try this below code

$name="Brian Lara"
$pattern = '/\w+\s[a-zA-Z]/';
preg_match($pattern,$name,$match);
echo $match[0];

Ouput

Brian L

Upvotes: 1

pp19dd
pp19dd

Reputation: 3633

Regexp - makes sure it hits the second word with /U modifier (ungreedy).

$t = "Brian Spelling something else";
preg_match( "/(.*) ./Ui", $t, $r );
echo $r[0];

And you get "Brian S".

Upvotes: 1

Aelios
Aelios

Reputation: 12137

Split your string with explode function and substring the first character of the second part with substr function.

$explodedString = explode(" ", $strName1);

$newString = $explodedString[0] . " " . substr($explodedString[1], 1);

Upvotes: 2

Rob Hruska
Rob Hruska

Reputation: 120286

  1. Find the index of the space with strpos
  2. Extract the string from the beginning to that index + 2 with substr

Also consider how you might need to update your logic for names like:

  • H. G. Wells
  • Martin Luther King, Jr.
  • Cher

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

<?php
$strName1 = "Brian Spelling";
$strName1 = substr($strName1, 0, strpos($strName1, ' ')+2);
echo $strName1;

prints

Brian S

Upvotes: 5

Related Questions