0

I have multiple lines like this in a file:

Platform
  value:  router
Native VLAN
  value:  00 01 

How can I use PHP to find 'Platform' and return the value 'router'

Currently I am trying the following:

$file = /path/to/file
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$value.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found Data:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No Data to look over";
}
1
  • 1
    If the file follows a specific format already you should use a parser. IE, is it a .yml? Commented Jul 29, 2015 at 1:10

2 Answers 2

3

Heres another simple solution

<?php
  $file = 'data.txt';
  $contents = file($file, FILE_IGNORE_NEW_LINES);
  $find = 'Platform';
  if (false !== $key = array_search($find, $contents)) {
      echo 'FOUND: '.$find."<br>VALUE: ".$contents[$key+1];
  } else {
      echo "No match found";
  }
?>

returns

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

No worries mate, just mark your question as 'Answered'
Thanks! Just couldn't quite figure it out.
@netpihelper You're welcome and Welcome to Stack ;-)
0

Here is a really simple solution with explode. Hope it helps.

function getValue($needle, $string){

    $array = explode("\n", $string);

    $i = 0;
    $nextIsReturn = false;

    foreach ($array as $value) {
        if($i%2 == 0){
            if($value == $needle){
                $nextIsReturn = true;
            }
        }else{
            // It's a value
            $line = explode(':', $value);
            if($nextIsReturn){
                return $line[1];
            }
        }
        $i++;
    }
    return null;
}

$test = 'Platform
          value:  router
        Native VLAN
          value:  00 01 ';

echo getValue('Platform', $test);

If the trailing spaces are a problem for you, you can use trim function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.