php - 正则表达式删除字符串上的字母或数字之前和之后的所有内容
问题描述
我正在使用 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);
我真的很难找到一种方法来删除最后一个字母/数字之后的任何内容。
有人可以帮我吗?如果之前和之后在一个正则表达式上,那就更好了。欢迎任何其他使我的代码更好的建议!
谢谢
解决方案
尝试:
$string = 'abc87#@-';
echo preg_replace('/^([a-zA-Z0-9]*).*$/', '$1', $string);
印刷:
abc87
这个想法是,在扫描字符串abc87#@-
时,abc87
成为捕获组 1 并且#@-
是其他所有内容(即.*
)。因此,正则表达式匹配整个字符串,因此您只需使用捕获组 1 替换整个字符串。
推荐阅读
- android - 从一个信号接收 url
- excel-formula - 假设每月付款随着通货膨胀而增加,我如何计算未来的投资增长?
- docker - Npm install 特定版本在 Dockerfile 中不起作用
- powershell - Shell 启动器脚本中的 PowerShell 错误
- python - pyPSA 仅优化调度
- html - 模糊的小尺寸图像
- php - 如何从 curl 响应中提取值
- javascript - 当我只有变量名作为字符串时如何获取变量的值?
- c# - 为什么我在使用 C# 调用 OCX C++ 代码时遇到问题
- python - 从 Git 导入 Python 包时出现“ModuleNotFoundError”