Reputation: 1362
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
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
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
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
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
Reputation: 120286
strpos
substr
Also consider how you might need to update your logic for names like:
Upvotes: 2
Reputation: 96159
<?php
$strName1 = "Brian Spelling";
$strName1 = substr($strName1, 0, strpos($strName1, ' ')+2);
echo $strName1;
prints
Brian S
Upvotes: 5