2014-02-25 76 views
0

我正在做一些數據的解析操作。我正在從數據庫中獲取這一行。 在這一行: [ ]這個東西是作者姓名。可以有多個作者。在那之後[ ],到第一個,的末尾,有作者大學。解析一個嵌套的句子,並與它們相關PHP

實施例線路

[Joseph, Susan; Forsythe, Stephen J.] Nottingham Trent Univ, Pathogen Res Ctr, Sch Sci & Technol, Nottingham NG11 8NS, England. %#[Cetinkaya, Esin; Ayhan, Kamuran] Oxford Univ, Fac Engn, Dept Food Engn,06110 8NS, England.

例如,對於這條線,所期望的輸出應爲:

Susan Joseph : Nottingham Trent Univ
Stephen J. Forsythe : Nottingham Trent Univ
Esin Cetinkaya : Oxford Univ
Kamuran Ayhan : Oxford Univ

這裏是我現在做:

enter image description here

我的代碼

while($row = mysqli_fetch_array($result)) 
     { 
     echo "<br>"; 
     echo $row['Correspounding_Author'] ; 
     echo "<br>"; 
     $pattern = '~(?<=\[|\G;)([^,]+),([^;\]]+)~'; 
     if (preg_match_all($pattern, $row['Correspounding_Author'], $matches, PREG_SET_ORDER)) { 
     print_r(array_map(function($match) { 
      return sprintf('%s %s', ltrim($match[2]), ltrim($match[1])); 
     }, $matches)); 

     } 
} 

This code is taking the authors from that line but i cannot related them with their universities

任何幫助appriciated。

回答

2

好了,這個工程:

$teststring = '[Joseph, Susan; Forsythe, Stephen J.] Nottingham Trent Univ, Pathogen Res Ctr, Sch Sci & Technol, Nottingham NG11 8NS, England. %#[Cetinkaya, Esin; Ayhan, Kamuran] Oxford Univ, Fac Engn, Dept Food Engn,06110 8NS, England.'; 

preg_match_all('/\[([^\]]+)]([^,]+)/', $teststring, $matches, PREG_SET_ORDER); 

foreach ($matches as $match) { 
    $authors = explode(";", $match[1]); 
    foreach ($authors as $author) { 
     echo preg_replace("/([^,]+),\s?(.*)/", "$2 $1", $author)." : ".$match[2]."<br />"; 
    } 
} 

輸出:

Susan Joseph : Nottingham Trent Univ 
Stephen J. Forsythe : Nottingham Trent Univ 
Esin Cetinkaya : Oxford Univ 
Kamuran Ayhan : Oxford Univ 

工作的代碼示例:

http://sandbox.onlinephpfunctions.com/code/1f9b68427fa71f74c3e6b775a3dbc3202f2c0d4a