Preg_match to match phone number - php

I have a csv file with about 2000 websites in it, I have a script working that file_get_contents of each site, and looks for a phone number.
My preg match is not working!!??
I need to find the exact number string 800-885-7505
I tried:
preg_match('/^800-885-7505$/', $page, $matches);
But didnt work.... Can anyone tell me why?
Thank you!
I tried:
<?
$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$page = file_get_contents("http://www.".$line[0]);
preg_match('/800-885-7505/', $page, $matches);
echo "http://www.".$line[0]." = ".$matches[1] . "<br><br>";
}
fclose($file);
?>
This DID work, I have the same script looking for what iframe is on a page, and it works great:
<?
$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$page = file_get_contents("http://www.".$line[0]);
preg_match('/<iframe.*src=\"(.*)\".*><\/iframe>/isU', $page, $matches);
if (($matches[1]!=="http://www.url.com/lmapp.html") && ($matches[1]!=="http://www.url.com/mc_NewApp2.html"))
{echo "http://www.".$line[0]." = ".$matches[1] . "<br><br>";}
}
fclose($file);
?>
So I thought I all needed to do was get a correct preg-match for the phone number

You can use:
preg_match('/800-885-7505/', $page, $matches);
or faster:
if ( strpos('800-885-7505',$page) !== false )

Related

How to find multiple lines from file with PHP?

I'm writing a PHP script to search for a few lines in a pcap file. This pcap file will be piped through tail -> PHP.
I need to find a few lines like (Host: www.google.com) or (Domain: amazon.com) etc..
I'm new with PHP and struggling to get this code working, the actual output of all the fetched data need to be inserted into a SQL DB. I've used regex to filter out the binary stuff from the pcap.
I've tried multiple loops like the wile, foreach, for, but I'm not getting the clue how to do this in my script.
The code that I have so far is:
<?php
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search1 = 'Location';
$search2 = 'Host:';
$search3 = 'User';
$search4 = 'Cookie';
$search5 = 'Domain:';
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
if(strpos($buffer, $search1) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
fclose($handle);
}
?>
I've read many posts on the internet, but couldn't find any solution or I've not enough knowledge about PHP to get this done. Can anyone help me with this?
If it's working for first then loop it think about algorithm always
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search = ['Location','Host:','User','Cookie','Domain:'];
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
foreach($search as $seek){
if(strpos($buffer, $seek) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
}
fclose($handle);
}
?>

Why is str_replace not working correctly

In my directory I have a list.csv of the form:
RP2015, active
Hope, paused
Process99, active
I'm writing a php script to allow a web user to switch the different lines from 'active' to 'paused' and back. Unfortunately I've hit a snag. My current code is live at: http://whitewaterwriters.com/Driver/index.php
and it looks like this
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
For some reason the replace is not firing. The event is captured, the correct target and replace strings are (I think) generated, but the replace is NOT coming out. The output I get is:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
Can anyone tell me what's going on?
EDIT:
The current list.csv is exactly:
RP2015, active
`
Try this:-
$fp = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$replacement = str_replace("active", "paused", $fp);
$numbytes = fwrite($handle, $replacement);
fclose($handle);
The thing I had forgotten is that html squashes consecutive spaces together which is why the $target looked like it was fine. Actually:
$data[0].", ".$data[1]
only needed to be
$data[0].",".$data[1]
Because there was a space left over from the csv parsing. I'll make the code a bit more robust to that in future.
For the interested - this helper function I wrote helped me locate the error:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
It converts a string to a sequence of ascii codes do you can make sure, for example, that quote characters are the ones you think they are...

How can I get the total number of rows in a CSV file with PHP?

Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
echo $row;
}
Create a new file reference using SplFileObject:
$file = new SplFileObject('test.csv', 'r');
Try to seek to the highest Int PHP can handle:
$file->seek(PHP_INT_MAX);
Then actually it will seek to the highest line it could in the file, there is your last line and the last line + 1 is equals to your total lines:
echo $file->key() + 1;
Tricky, but this will avoid you from loading the file contents into memory, which is a very cool thing to do when dealing with really large files.
Here's another option using file() to read the entire file into an array, automatically parsing new lines etc:
$fp = file('test.csv');
echo count($fp);
Also, since PHP5, you can pass in the FILE_SKIP_EMPTY_LINES... to skip empty lines, if you want to:
$fp = file('test.csv', FILE_SKIP_EMPTY_LINES);
Manual: http://php.net/manual/en/function.file.php
Try
$c =0;
$fp = fopen("test.csv","r");
if($fp){
while(!feof($fp)){
$content = fgets($fp);
if($content) $c++;
}
}
fclose($fp);
echo $c;
I know that this is pretty old, but actually I ran into the same question.
As a solution I would assume to use linux specific logic:
$rows = shell_exec('$(/bin/which cat) file.csv | $(/bin/which tr) "\r" "\n" | $(which wc) -l');
NOTE: this only works for linux only and this only should be used if you are 100% certain that your file has no multiline-cells
CSV rows are separated by line breaks. Therefore, split the rows by line breaks, and you will get an array of rows, which is countable.
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$rows = explode("\n", $fp);
$length = count($rows);
echo $length;
}
Note; none of higher-upvoted solutions that count lines in the file are reliable, as they are only counting the lines, not the csv entries (which can contain newline characters)
I'm using a similar solution to op, and it works perfectly, but with op's code the while part can break on empty lines, which is potentially his problem.
So it looks like this (edited op's code)
$rowCount=0;
if (($fp = fopen("test.csv", "r")) !== FALSE) {
while(!feof($fp)) {
$data = fgetcsv($fp , 0 , ',' , '"', '"' );
if(empty($data)) continue; //empty row
$rowCount++;
}
fclose($fp);
}
echo $rowCount;
I find this the most reliable:
$file = new SplFileObject('file.csv', 'r');
$file->setFlags(
SplFileObject::READ_CSV |
SplFileObject::READ_AHEAD |
SplFileObject::SKIP_EMPTY |
SplFileObject::DROP_NEW_LINE
);
$file->seek(PHP_INT_MAX);
$lineCount = $file->key() + 1;
I know this is an old post, but I've been googling this issue, and found that the only problem with the original code was that you need to define $row outside the while loop, like this:
if (($fp = fopen("test.csv", "r")) !== FALSE) {
$row = 1;
while (($record = fgetcsv($fp)) !== FALSE) {
$row++;
}
Just in case it helps someone :)
echo $row;
}
In case you are getting the file from a form
$file = $_FILES['csv']['tmp_name'];
$fp = new SplFileObject($file, 'r');
$fp->seek(PHP_INT_MAX);
echo $fp->key() + 1;
$fp->rewind();
Works like charm!!!!!!!!!!!!!!!!!!
$filename=$_FILES['sel_file']['tmp_name'];
$file=fopen($filename,"r");
$RowCount=0;
while ((fgetcsv($file)) !== FALSE)
{
$RowCount++;
}
echo $RowCount;
fclose($file);

Replace a particular line in a text file using php?

I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.
I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.
This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!
After some edit seems to be working now. I am debugging to see if any errors.
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, '|')
/* manipulate $data array here */
}
fclose($handle);
So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php
$fp = fopen('contacts.tmp', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :
$writing = fopen('contacts.tmp', 'a');

CSV file read fail (PHP )

I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>

Categories