我想從左側獲取所有文本,直到出現空格,然後在空格後再獲取一個字符。從左側獲取字符,直到空格再後面還有一個字符
例如: 「布賴恩拼寫」將「布賴恩S」
我怎樣才能做到這一點在PHP?
在ASP代碼如下所示:
strName1=left(strName1,InStr(strName1, " ")+1)
我想從左側獲取所有文本,直到出現空格,然後在空格後再獲取一個字符。從左側獲取字符,直到空格再後面還有一個字符
例如: 「布賴恩拼寫」將「布賴恩S」
我怎樣才能做到這一點在PHP?
在ASP代碼如下所示:
strName1=left(strName1,InStr(strName1, " ")+1)
<?php
$strName1 = "Brian Spelling";
$strName1 = substr($strName1, 0, strpos($strName1, ' ')+2);
echo $strName1;
打印
Brian S
謝謝你這麼多的解釋!這比其他人提供的例子要好得多。 – compcobalt
分裂您的字符串與explode
功能並用substr
函數子字符串第二部分的第一個字符。
$explodedString = explode(" ", $strName1);
$newString = $explodedString[0] . " " . substr($explodedString[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數組中
Regexp - 確保它碰到第二個單詞用/ U修飾符(非語言)。
$t = "Brian Spelling something else";
preg_match("/(.*) ./Ui", $t, $r);
echo $r[0];
而且你得到了「Brian S」。
試試這個下面的代碼
$name="Brian Lara"
$pattern = '/\w+\s[a-zA-Z]/';
preg_match($pattern,$name,$match);
echo $match[0];
輸出繼電器
Brian L
優秀的,謝謝你這麼多VolkerK – compcobalt