PHP nextLine with String - php

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!

// 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.

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

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:'';
?>

Related

Why doesn't this simple PHP preg_match() function work?

Although a $_FILES array is not shown, this is intended for file upload, I have had problems with file uploading so I was not able to get the [type] part of the $_FILES array yet... but this is just a simple problem of why isn't this function working...
<?php
function getExtension() {
// global $testFile;
$extension = "./mp3/"; // also tried simply mp3 without the forwards slashes
$testFile = "song.mp3";
if(preg_match($extension, $testFile)) {
echo "match found";
}else {
echo "no match found";
}
}
getExtension();
?>
Do this:
$extension = "/mp3$/";
or
$extension = "/\.mp3$/";
ONLINE EXAMPLE
Reason being, you need the delimiters to begin and end your expression with (those are the slashes, though the can be any character) and can't have anything ahead of or behind them. The "$" will mean, find the string between the delimiters at the end of the string.
You can keep the period by escaping it (or else it will mean any character once, meaning testmp3 would be a match).
But really the best answer is as suggested in the comments - php's pathinfo() - since you are parsing a filename. Though in certain cases, you may want to do other tests for security, like check the mimetype.
If you want to keep the period, make sure you escape it.
$pattern = "/\.mp3$/";
There is a mistake in your Regular Expression :
"./mp3/" => "/\.mp3$/"
Result :
<?php
function getExtension() {
// global $testFile;
$extension = "/\.mp3$/"; // also tried simply mp3 without the forwards slashes
$testFile = "song.mp3";
if(preg_match($extension, $testFile)) {
echo "match found";
}else {
echo "no match found";
}
}
getExtension();
?>
ONLINE EXAMPLE

Recursive Web Link Search in PHP

I am trying to do recursive web link search using PHP, but the code doesn't seem to work. I get a timeout error.
function linksearch($url)
{
$text = file_get_contents($url);
if (!empty($text))
{
$res1 = preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",
$text,
$matches);
if ($res1)
{
foreach(array_unique($matches[0]) as $link)
{
linksearch($url);
}
}
else
{
// echo "No links found.";
}
}
}
You have a neverending loop there in your function, because you call your function again inside your function.
linksearch($url);
You need a condition to terminate your function. That ain't no recursion, because on each iteration the input would change and end until some condition. Now it's the same all the time - $url.
Why don't you first save the page locally, and tune your script fetching a local test file, instead of having to run a remote call every time. You won't get a timeout error from the evaluation code that follows your file_get_contents(), unless the HTML file is humungously large.

Validate a domain name with GET parameters using a REGEX

I am trying to validate if a domain does have GET parameters with preg_match and and a REGEX, which i require it to have for my purposes.
What I have got working is validating a domain without GET parameters like so:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$/", 'domain.com')) {
echo 'true';
} else {
echo 'false';
}
I get true for this test.
So far so good. What I am having trouble with is adding in the GET parameters, Amongst a number of REGEX's I have tried with still no luck is the following:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}([/?].*)?$/", 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
Here i get false returned and hence am not able to validate a domain with GET parameters which are required.
Any assistance will be much appreciated ^^
Regards
This code is not tested, but I think it should work:
$pattern = "([a-z0-9-.]*)\.([a-z]{2,3})"; //Host
$pattern .= "(\?[a-z+&\$_.-][a-z0-9;:#&%=+\/\$_.-]*)?"; //Get requests
if (preg_match($pattern, 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
What is the advantage of using a REGEX?
Why not just
<?php
$xGETS = count($_GET);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
// PHP 5.2+
$xGETS = filter_var('http://domain.com?test=test', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
Your first regular expression will reject some valid domain names (e.g. from the museum and travel TLDs and domain names that include upper case letters) and will recognize some invalid domain names (e.g. where a label or the whole domain name is too long).
If this is fine with you, you might just as well search for the first question mark and treat the prefix as domain name and the suffix as "GET parameters" (actually called query string).
If this is not fine with you, a simple regular expression will not suffice to validate domain names, because of the length constraints of domain names and labels.

check preg_match results against other values?

I need some help with my PHP script.
So, here is the deal.
I have a preg_match which checks for the following text in a .txt file that changes every 30minutes or so: LYBE_TWR,LYBE_APP,LYBA_CTR,LYPG_TWR,LYPG_APP,LYTV_TWR,LYNI_APP)
It runs perfectly and gets the above strings if they are present.
But I need to do even further and check which of the seven combinations have been found because not all are present at all times.
Example:
The current text file contains LYBE_TWR, LYBE_APP, LYPG_TWR. The preg_match does its thing and I can echo the 3 values but I need this.
LYBE_TWR : PRESENT/NOT PRESENT
LYBE_APP: PRESENT/NOT PRESENT
LYBA_CTR PRESENT/NOT PRESENT
LYPG_TWR PRESENT/NOT RESENT
etc.
So if it is found in the text file it echos present, if not it echoes not present.
The correct results would be:
LYBE_TWR : PRESENT
LYBE_APP: PRESENT
LYBA_CTR NOT PRESENT
LYPG_TWR PRESENT
If I do for example if ($string == "LYBE_TWR") { echo 'present'; } else { echo 'not present'} it will echo the correct value for the LYBE_TWR but it will say not present for the later as they are not actually the one I if-ed for.
I hope you understand as I myself am not sure anymore (rofl)
edit: here is the current code..bare in mind it is still WIP so not finished and there will be some errors http://pastebin.com/z1r4A78E
Thanks.
This is the code working on the assumption that you're interested if the string appeared in your file, not in the line. I split the strings into prefixes and suffixes, and I'm ignoring any numerical values. I didn't copy all your code, for readability's sake
$prefixes = array("LYBA", "LYBE", "LYPG", "LYNI", "LYTV");
$suffixes = array("TWR", "APP", "CTR");
foreach($prefixes as $prefix)
{
foreach($suffixes as $suffix)
{
$results[$prefix."_".$suffix] = 0;
}
}
if(preg_match('/^('.implode("|",$prefixes).'|)_[A-Z0-9]*_*('.implode("|",$suffixes).')/', $line, $matches))
{
(... your code ...)
$match_string = $matches[1]."_".$matches[2];
$results[$match_string]++;
}
foreach($results as $key => $value)
{
echo $key;
if($value > 0)
{
echo " PRESENT";
}
else
{
echo " NOT PRESENT";
}
echo "<br/>";
}

preg_match and reg expression using alphanumeric, commas, periods, exclamations, etc

I am having one hell of a time coming up with a decent way make this if statement search a file for these codes. I set up the text file to read from as such:
myfile.txt
r)
0Y7
1a6
q.
#g
#(
#a
!P
T[
V}
0,
Here is a brief of what I got going.
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if ( preg_match('/^[a-zA-Z0-9,]+$/',$result['fmbushels_itemCode'], $subject) ) {
Basically I am trying to search the text file line by line to see if the whole string exists. They are case sensitive as well.
$result['fmbushels_itemCode'] is from a sql query and always returns a code like the above in the text.
I'd appreciate any help on this. If someone knows a better way of doing this or a different command, I'd be willing to give that a shot as well :)
edit:
private function _fvShareBushels() {
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if (count($vShareArray) > 0) {
$vCntMoves = count($vShareArray);
for ($vI = 0;$vI < $vRunMainLoop;$vI++) {
sell $result['fmbushels_itemCode']);
}
}
}
This is a snippet of a big code. I had to rip most out because of post limitation. The area I could be working with is:
if (count($vShareArray) > 0) {
If I could make this something like:
if (count($vShareArray) > 0 && $result['fmbushels_itemCode'] **is not in** $subject) {
If you want to do line by line, use the file() function.
$f = file(fvManager_Path . 'myfile.txt');
foreach($f AS $line){
// $line is current line at file
}
I'm not to sure if you understand completely how preg_match works. The first parameter is the regular expression pattern, the second is what you want to match the pattern to, and the third is an array of matches. So for every valid pattern matched in the second parameter a new index on the array is created.
I'm not 100% on what you're trying to accomplish. Are you trying to see if the $result['fmbushels_itemCode'] exists in the file?
If the above is the correct case you simply just need to do something like:
$f = file('myfile.txt');
array_map('trim', $f);
if(in_array($result['fmbushels_itemCode'], $f)){
// success
}

Categories