【问题标题】:php regular expression extract part of textphp正则表达式提取部分文本
【发布时间】:2013-03-08 20:56:15
【问题描述】:

我需要从数据库中提取,其中一列中的记录以这种方式组合: 第一个字母(名字 1)。姓 1,第一个字母(名字 2)。姓氏2,....

这是我尝试解决的示例...

     $text2= "T. Toth, M. A. Carlo de Miller, T. Stallone";
     $keywords = preg_split("/,/", "$text2");

     print_r($keywords);

    //I got a result in this way:

    //Array ( [0] => T. Toth [1] => M. A. Carlo de Miller [2] => T. Stallone ) 

    // I want a result of the form :

    //Array ( [0] => T [1] => Toth [2] => M. A. [3] => Carlo de Miller [4] => T  and    so on....

有人可以知道如何进行?即使它可以在 MYSQL 中

【问题讨论】:

  • 这并不容易做到。你将如何区分 T.M. 与 T.Toth 和 M.A.Carlo?两者都是首字母,但显然您希望它们区别对待

标签: php extract


【解决方案1】:

另一种变体:

$text2= "T. Toth, M. A. Carlo de Miller, T. Stallone";
$result = array();
foreach (explode(",",$text2) as $row)
{
  $row = explode(".",$row);
  $last = array_pop($row);
  $result[] = join(".",$row).".";
  $result[] = $last;
}
print_r($result);

结果:

Array ( [0] => T. [1] => Toth [2] => M. A. [3] => Carlo de Miller [4] => T. [5] => Stallone )

【讨论】:

    【解决方案2】:

    我认为这个正则表达式应该或多或少做你想做的事:

    /
      (?:^|,)           # Start of subject or comma
      \s*               # Optional white space
      ((?:[a-z]\.\s*)+) # At least one occurrence of alpha followed by dot
      \s*               # Consume trailing whitespace
    /ix
    

    当与PREG_SPLIT_NO_EMPTYPREG_SPLIT_DELIM_CAPTURE 捕获标志结合使用时,此表达式将获得您想要的结果,唯一需要注意的是它还会捕获一些前导/尾随空格。我看不出有什么办法可以避免这种情况,而且当你使用结果时很容易将其修剪掉。

    $str = 'T. Toth, M. A. Carlo de Miller, T. Stallone';
    $expr = '/(?:^|,)\s*((?:[a-z]\.\s*)+)\s*/i';
    $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
    
    $keywords = preg_split($expr, $str, -1, $flags);
    
    print_r($keywords);
    

    See it working

    【讨论】:

      【解决方案3】:

      preg_split 可能不适合此功能。用preg_match_all试试这个:

      $text2= "T. Toth, M. A. Carlo de Miller, T. Stallone";
      preg_match_all("/\w{2,}(?:\s\w{2,})*|\w\.(?:\s\w\.)*/i", $text2, $matches);
      print_r($matches[0]);
      

      这会挑选出姓名和首字母缩写,同时省略前导/尾随空格。

      第一个匹配全名:\w{2,}(?:\s\w{2,})*

      第二场比赛首字母:\w\.(?:\s\w\.)*

      结果:

      Array ( [0] => Array ( [0] => T. [1] => Toth [2] => M. A. [3] => Carlo de Miller [4] => T. [5] => Stallone ) )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-25
        • 1970-01-01
        • 1970-01-01
        • 2012-02-11
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多