在MySQL数据库中,我有一个名称列表,如
我要把那份名单
所谓格式,我的意思是我只想要姓氏的“主”部分去掉任何
我意识到,在某些情况下,这是“改变”的人的名字,但它并没有被使用的任何方式,他们看到。
现在我正在做这样的事情:
$toReplace = array('.', ',', '-', ' jr', ' sr', ' MD', ' DO', "'", ' ');
//For each result from my query
$lname = str_replace($toReplace, '', $row_rsgetUsers['lname']);
$lname = strtolower($lname);然后,过一段时间,会出现一个类似于Wright CISA的名称,所以我必须更新我的$toReplace数组来解释这个问题。(我无法控制姓名的输入)
这是进行此操作的最佳方法吗?还是应该使用更好的方法/库来消除偶尔手动更新$toReplace数组的需要?
发布于 2014-03-24 13:59:02
这应该照你说的做。虽然你可以在这里找到它:替换除字母、数字、空格和下划线以外的所有字符 如何删除PHP中空格后的所有内容?
<?php
$user_list = array('Smith', 'Frank', 'Dent MD', 'Smith Sr.', 'Jones, jr.', 'Smith-Jones', "O'Toole");
print_r($user_list);
$string = "O'Toole";
$temp_array = array();
foreach($user_list as $user_string){
//remove special chars and convert Upper case letters to lower case
$string = strtolower(preg_replace("/[^ \w]+/", "", $user_string));
//remove everything after space, case example: Jones, jr.
$string = explode(' ', $string);
$string = $string[0];
//assign "standartized?" string
$temp_array[] = $string;
}
print_r($temp_array);
?>
Array
(
[0] => Smith
[1] => Frank
[2] => Dent MD
[3] => Smith Sr.
[4] => Jones, jr.
[5] => Smith-Jones
[6] => O'Toole
)
Array
(
[0] => smith
[1] => frank
[2] => dent
[3] => smith
[4] => jones
[5] => smithjones
[6] => otoole
)发布于 2014-03-24 14:02:50
这是一个函数,它将用ASCII字符替换所有非ASCII字符,使字符串小写等( 源CookBook )。
$names = array( 'Smith', 'Frank', 'Dent MD', 'Smith Sr.', 'Jones, jr.', 'Smith-Jones', "O'Toole" );
foreach( $names as &$value ) {
$value = slugify( $value );
}
print_r( $names );
function slugify( $text ) {
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
/**
* //IGNORE//TRANSLIT to avoid errors on non translatable characters and still translate other characters
* //TRANSLIT to out_charset transliteration is activated
* //IGNORE, characters that cannot be represented in the target charset are silently discarded
*/
$text = iconv('utf-8', 'ASCII//IGNORE//TRANSLIT', $text);
$text = strtolower(trim($text));
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
return empty($text) ? '' : $text ;
}输出:
Array
(
[0] => smith
[1] => frank
[2] => dent-md
[3] => smith-sr
[4] => jones-jr
[5] => smith-jones
[6] => o-toole
)https://stackoverflow.com/questions/22611052
复制相似问题