user1062058
user1062058

Reputation: 275

PHP nextLine with String

I wrote a php search script on my site for checking to see if a package exists in a text file or not (I used file_get_contents.) It takes what the user entered and combines it with the string 'BUILD: ' Below is an example of the file and I'll explain in the paragraph following it:

BUILD: packageA
URL: www.package-a.com

BUILD: packageB
URL: www.package-b.com

BUILD: packageC
URL: www.package-c.com

So if a user were to search "packageB", it would be combined with "BUILD: " making the variable I'm testing with have the value: "BUILD: packageB". I have a conditional saying if that string exists or not; everything's working good on that end.

My question/problem is how can I list the URL: line beneath it with an echo? I've been testing some ideas with strlen() and I can't seem to get it and the text file has different strlens for entry. Is there a way to make PHP force a "nextLine()" if there is such a thing... does PHP recognize return delimits?

Thank you!

Upvotes: 2

Views: 1310

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

If you are open to alternative methods, then here is a simpler/faster solution.

builds.php

<?php 
$builds=array("packageA"=>"www.package-a.com",
              "packageB"=>"www.package-b.com",
              "packageC"=>"www.package-c.com",
              "packageD"=>"www.package-d.com");
?>

OtherScript.php

<?php 
if(isset($_POST['package'])){
    include('./builds.php');
    if(array_key_exists($_POST['package'], $builds)){
        $notice="You Selected: ".$_POST['package']." Url:".$builds[$_POST['package']];
    }else{
        $notice="Package Not Found";
    }
}


echo (isset($_POST['package']))?$notice:'';
?>

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88647

// The string you are searching for
$package = 'packageB';

// Get the file into an array
$data = file('myfile.txt');

// Loop the data
for ($i = 0, $found = FALSE; isset($data[$i]); $i++) {
  if (trim($data[$i]) == "BUILD: $package") { // We found the one we're looking for
    echo trim($data[++$i]); // Echo the next line
    $found = TRUE;
    break; // Stop looping
  }
}

if ($found) {
  echo "<br />\nI found the URL on line $i";
} else {
  echo "I didn't find it!";
}

file() gets the file data as an array where each element is one line of the file, unlike a single string like file_get_contents() returns.

Upvotes: 2

Alex Howansky
Alex Howansky

Reputation: 53563

You can do a regex with the /m modifier which makes it match across multiple lines, then use a parenthesized pattern to capture the line following the match:

if (preg_match_all('/BUILD: packageB\n(.+)\n/m', file_get_contents('file.txt'), $match)) {
    foreach ($match[1] as $match) {
        echo "$match\n";
    }
}

Outputs:

URL: www.package-b.com

Upvotes: 1

Related Questions