Damir
Damir

Reputation: 56199

Find line which contains given word and return substring

I have file with lines which look like word_1:word_2 (for example file looks like

username:test
password:test_pass
dir:root

)

. How to find from file word_2 when I have word_1 ? Is there in PHP contains and substring like in Java ?

Upvotes: 0

Views: 517

Answers (2)

KingCrunch
KingCrunch

Reputation: 131861

You dont describe your file format very well, but maybe its formatted like a csv-file

$file = fopen('filename', 'r');
while (($line = fgetcsv($file, 1024, ':')) !== false) {
  if (in_array($needle, $line)) {
    return $line;
  }
}
return null;

If you assume, that you are always looking for the first field, you can replace in_array(/* .. */) with $line[0] === $needle.

Update: After the edit of the question, I would suggest something like this, as it seems, that the file is just a kind of csv file (with ":" instead of ",").

function getValue ($key, $filename) {
  $file = fopen('filename', 'r');
  while (($line = fgetcsv($file, 1024, ':')) !== false) {
    if ($line[0] === $key) {
      fclose($file);
      return $line[1];
    }
  }
  fclose($file);
  return null;
}

Also consider reading the file once and then just access the values

class MyClass {
  private $data = array();
  public function __construct ($filename) {
    $file = fopen('filename', 'r');
    while (($line = fgetcsv($file, 1024, ':')) !== false) {
      $this->data[$line[0]] = $line[1];
    }
    fclose($file);
  }
  function getValue ($key, $filename) {
    return array_key_exists($key, $this->data)
           ? $this->data[$key];
           : null;
  }
}  

Upvotes: 1

Ikke
Ikke

Reputation: 101231

To find out if a string contains another string, use strpos()

Note that you need the !== when using the strpos() function because of the fact that if the string starts with the string you are looking for, it will return 0 which is the same as false.

if(strpos($mystring, 'word_1') !== false)
{
    //$mystring contains word_1
}

And I would use the explode() function to split the string and get the second part.

Upvotes: 3

Related Questions