I am very new guy at PHP and trying to parse a line from database and get some neccesarray information in it.
EDIT :
I have to take the authors names and surnames like for first example line : the expected output should be :
Ayse Serap Karadag
Serap Gunes Bilgili
Omer Calka
Sevda Onder
Evren Burakgazi-Dalkilic
LINE
[Karadag, Ayse Serap; Bilgili, Serap Gunes; Calka, Omer; Onder, Sevda] Yuzuncu Yil Univ, Sch Med, Dept Dermatol. %#[Burakgazi-Dalkilic, Evren] UMDNJ Cooper Univ Med Ctr, Piscataway, NJ USA.1
I take this line from database. There are some author names which i have to take. The author names are written in []
. First their surnames which is separated with ,
and if there is a second author it is separated with ;
.
I have to do this action in a loop because i have nearly 1000 line like this.
My code is :
<?php
$con=mysqli_connect("localhost","root","","authors");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Correspounding_Author FROM paper Limit 10 ");
while($row = mysqli_fetch_array($result))
{
echo "<br>";
echo $row['Correspounding_Author'] ;
echo "<br>";
// do sth here
}
mysqli_close($con);
?>
I am looking for some methods like explode()
substr
but as i mentioned at the beginning I cannot handle this nested sentence.
Any help is appreciated.
The following should work:
$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));
}
It's a single expression that matches items that:
[
or continue where the last match ended followed by a semicolon,See also: PCRE Assertions.
Array
(
[0] => Ayse Serap Karadag
[1] => Serap Gunes Bilgili
[2] => Omer Calka
[3] => Sevda Onder
[4] => Evren Burakgazi-Dalkilic
)
The code inside your while
loop should be:
preg_match_all("/\\[([^\\]]+)\\]/", $row['Correspounding_Author'], $matches);
foreach($matches[1] as $match){
$exp = explode(";", $match);
foreach($exp as $val){
print(implode(" ", array_map("trim", array_reverse(explode(",", $val))))."<br/>");
}
}