【问题标题】:Regex to remove everything BEFORE and AFTER letter or numbers on a string正则表达式删除字符串上的字母或数字之前和之后的所有内容
【发布时间】: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


    【解决方案1】:

    试试:

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

    打印:

    abc87
    

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

    【讨论】:

      猜你喜欢
      • 2011-09-08
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多