【发布时间】:2020-05-31 04:19:51
【问题描述】:
我正在使用 PHP 制作一个函数来清理名称字符串。
所以,我有这样的名字:
$name_1 = ' \'Brian O\'Ril"*ley';
$name_2 = ' \' " José Sant\'Anna';
# Output expected:
# Brian O'Rilley
# José Sant'Anna
我的功能码:
function cleanName($string)
{
# --------------------------------------------------
# Remove everything before first letter and after last letter
# --------------------------------------------------
$string = preg_replace('/^[^A-Za-z0-9]+/','',$string);
# --------------------------------------------------
# Clean spaces
# --------------------------------------------------
$string = htmlentities($string,null,'utf-8');
$string = str_replace(' ',' ',$string);
$string = preg_replace('!\s+!',' ',$string);
$string = html_entity_decode($string);
# --------------------------------------------------
# Replace quotes
# --------------------------------------------------
$string = str_replace(array('`','´','´´','``','"'),'\'',$string);
$string = preg_replace("/'{2,}/","'",$string);
# --------------------------------------------------
# Remove everything but letters, single spaces, simple quotes, and ISO-8859-1 characters
# --------------------------------------------------
$string = preg_replace('/[^A-Za-z0-9 \'\xC0-\xD6\xD8-\xF6\xF8-\xFF]+/u','',$string);
# --------------------------------------------------
# Upper case on fisrt letters
# --------------------------------------------------
$string = ucwords(strtolower($string));
# --------------------------------------------------
# Output
# --------------------------------------------------
return $string;
}
代码几乎完成了我需要的一切,但是:
# This one only removes BEFORE - I also need to remove AFTER
$string = preg_replace('/^[^A-Za-z0-9]+/','',$string);
我真的很难找到一种方法来删除最后一个字母/数字之后的任何内容。
有人可以帮我吗? 如果之前和之后在一个正则表达式上,那就更好了。 欢迎任何其他使我的代码更好的建议!
谢谢
【问题讨论】:
标签: php regex string character