Jump to content

[SOLVED] Need to extract a piece of data from a string


Yesideez

Recommended Posts

Hi, Wildbug has been helpful to supply a Regex string (I can't figure the damn things out) but I think I'm using the wrong PHP function...

 

This is my code:

<?php
  if ($arrGedcom=file('sample.ged')) {
    for ($i=0;$i<count($arrGedcom);$i++) {
      $arrGedcom[$i]=trim($arrGedcom[$i]);
    }
    if ($arrGedcom[0]=='0 HEAD') {
      for ($i=0;$i<count($arrGedcom);$i++) {
        $famcode=preg_replace('/@(.*?)@/','$1',$arrGedcom[$i]);
        echo $famcode.'<br />';
      }
    } else {echo 'ERROR: Not a valid GEDCOM file "'.$arrGedcom[0].'"';}
  } else {echo 'ERROR: Unable to open the file';}
?>

 

This is an extract of what the above script is beign run on:

1 FAMC @F2@
0 @F1@ FAM
1 HUSB @I1@
1 WIFE @I2@
1 CHIL @I3@
1 CHIL @I4@

 

This is what I'm getting:

1 FAMC F2
0 F1 FAM
1 HUSB I1
1 WIFE I2
1 CHIL I3
1 CHIL I4

 

This is what I want instead:

F2
F1
I1
I2
I3
I4

 

Many thanks in advance ;)

you're right, you should be using preg_match(), which will extract any subpattern matches:

 

<?php
  if ($arrGedcom=file('sample.ged')) {
    $arrGedcom = array_map('trim', $arrGedcom);

    if ($arrGedcom[0]=='0 HEAD') {
      foreach($arrGedcom AS $line)
      {
        $matches = array();
        preg_match('/@(.*?)@/', $line, $matches);
        echo $matches[1].'<br />';
      }
    } else {echo 'ERROR: Not a valid GEDCOM file "'.$arrGedcom[0].'"';}

  } else {echo 'ERROR: Unable to open the file';}
?>

 

if you anticipate more than one set of @-delimited strings, you'll need to change it to preg_match_all().  have a look in the manual at both array_map() and preg_match() for further details.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.