$data['full_name'] 存盤全名,例如 John Smith
目前我正在使用
$data['full_name'] = strtok($data['full_name'], " ");
這將為我轉換名字 - 例如約翰
我還想包括第二個名字 - 例如 John S
uj5u.com熱心網友回復:
我會在這里使用正則運算式替換:
$input = "John Michael Smith";
$output = preg_replace("/(?<=\s)(\w)\w*/", "$1", $input);
echo $output; // John M S
我使用了一個正則運算式模式,它將針對名字中除名字之外的所有單詞,并僅替換為第一個字母。此處使用的正則運算式模式表示匹配:
(?<=\s) assert that a space precedes (excludes the first name)
(\w) match and capture the first letter
\w* then consume the rest of the name, without matching
我們替換為$1,它只是名稱組件的第一個字母。
uj5u.com熱心網友回復:
使用此代碼段
<?php
$input = "John Smith";
$name = explode(" ", $input);
$formatted = "";
foreach ($name as $key => $value)
{
// code...
if ($key == 0) {
$formatted .= $value;
} else {
$formatted .= ' ' . substr($value, 0, 1);
}
}
echo $formatted;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417729.html
標籤:
上一篇:如何從單個陣列創建多個陣列?
