首页 > 解决方案 > 正则表达式删除字符串上的字母或数字之前和之后的所有内容

问题描述

我正在使用 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);

我真的很难找到一种方法来删除最后一个字母/数字之后的任何内容。

有人可以帮我吗?如果之前和之后在一个正则表达式上,那就更好了。欢迎任何其他使我的代码更好的建议!

谢谢

标签: phpregexstringcharacter

解决方案


尝试:

$string = 'abc87#@-';
echo preg_replace('/^([a-zA-Z0-9]*).*$/', '$1', $string);

印刷:

abc87

这个想法是,在扫描字符串abc87#@-时,abc87成为捕获组 1 并且#@-是其他所有内容(即.*)。因此,正则表达式匹配整个字符串,因此您只需使用捕获组 1 替换整个字符串。


推荐阅读