2012-10-18 24 views

回答

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

打印

Brian S 
+0

優秀的,謝謝你這麼多VolkerK – compcobalt

2
  1. 找到空間與strpos
  2. 指數從一開始提取字符串該指數+ 2與substr

而且考慮如何需要更新您的邏輯名稱類似:

  • 威爾斯
  • 馬丁·路德·金
  • 雪兒
+1

謝謝你這麼多的解釋!這比其他人提供的例子要好得多。 – compcobalt

2

分裂您的字符串與explode功能並用substr函數子字符串第二部分的第一個字符。

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

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

,只是爲了好玩採取周密羅布Hruska的的答案,你可以做這樣的事情:

$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; 

- 只是編輯,以便「雪兒」,將工作太

添加你想跳過的任何後綴添加到$ skip數組中

1

Regexp - 確保它碰到第二個單詞用/ U修飾符(非語言)。

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

而且你得到了「Brian S」。

1

試試這個下面的代碼

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

輸出繼電器

Brian L 
相關問題