我需要从数据库中提取数据,其中一列中的记录以这种方式组合:第一个字母(名字1)。姓氏1,第一个字母(姓氏2)。 Lastname2,....
这是我如何解决的示例...
$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中,也有人可以知道如何进行?
另一个变体:
$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 )
我认为这个正则表达式应该或多或少地满足您的要求:
/
(?:^|,) # 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_EMPTY
和PREG_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);
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 ) )