【发布时间】:2022-01-21 02:44:52
【问题描述】:
$data['full_name'] 存储全名,例如约翰·史密斯
目前我正在使用
$data['full_name'] = strtok($data['full_name'], " ");
这将为我转换名字 - 例如约翰
我还想包括第二个名字 - 例如约翰·S
【问题讨论】:
$data['full_name'] 存储全名,例如约翰·史密斯
目前我正在使用
$data['full_name'] = strtok($data['full_name'], " ");
这将为我转换名字 - 例如约翰
我还想包括第二个名字 - 例如约翰·S
【问题讨论】:
我会在这里使用正则表达式替换:
$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,它只是名称组件的第一个字母。
【讨论】:
使用这个代码sn-p
<?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;
【讨论】: