Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Example:

@article{ames2011pilot,
author = "Ames, S. C. and Tan, W. W. and Ames, G. E. and Stone, R. L. and Rizzo Jr and T. D. and Crook, J. E. and Williams, C. R. and Werch, C. E. and Clark, M. M. and Rummans, T. A.",
title = "A pilot investigation ",
journal = "Psycho‐oncology",
volume = "20",
number = "4",
pages = "435-440",
year = 2011
}

I need to get only title values which is between "".The ans should be, A pilot investigation.
I tried the following php code,but am getting all the values between double quotes not only title value.

PHP
<?php
$file=file("master.bib");
$m=array();
$c=count($file);
for($i=0;$i<$c;$i++){
//article-start
if((strpos($file[$i],"@article"))==0){
//title-start
if((strpos($file[$i],"title"))<=3){
preg_match('/\"(.*?)\"/',$file[$i],$m);
        echo $m[1];
        echo "<br>"           ;

//end-title
}
}
//end of article
}


I don't know what is the wrong here. Which is the efficient way to get the value between double quotes as I need.
Posted

1 solution

Your problem description reveals that you're looking to capture the string between double quotes when they're directly after title and between the braces of @article. Therefore, you can use this regex:
PHP
/@article{[^}]+title.*?\"([^"]*)\"/

Regex Explanation:
  • @article{ Matches an open @article string, along with the bracket.

  • [^}]+ Matches any amount of non-"}"s, effectively implying that our match is within the braces, and not outside the tag.


  • \"([^"]*)\" Matches a pair of double quotes, captures everything in them.



However, here's an optimized and more accurate regex just for you:
PHP
'/@article{(?>[^}t]+|t(?!itle\h*=))+title\h*=.*?\"(.*?)\"(?![^"\n]")/'


So you have:
PHP
$file = file("master.bib");
$m = array();

preg_match_all('/@article{(?>[^}t]+|t(?!itle\h*=))+title\h*=.*?\"(.*?)\"(?![^"\n]")/', $file, $m);
echo $m[1];
echo "<br>";</br>


Here's a regex demo.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900