PHP get names in a file after letters name: - php

I need a PHP script to print customer names in a file. There's hundreds of names and addresses but I want to print only the names with a maximum of 15 letters.
<?php
$file = file_get_contents('data-cust.txt');
$keyword = 'name';
$str = substr($file, strpos($file, $keyword) + strlen($keyword), 15);
echo $str;
?>
I tried using the above but only printed one name. How do I make it print all names?
Thanks.

If the names are on their own line, something like this should work.
<?php
$file = file('data-cust.txt');
foreach($file as $line) {
$keyword = 'name';
$str = substr($line, strpos($line, $keyword) + strlen($keyword), 15);
echo $str;
}

You need to open the file and read it then extract the names.
$file = fopen("data-cust.txt", "r");
$keyword = 'name';
$str = array() ;
if ($file) {
while (($line = fgets($file )) !== false) {
$name = substr($line, strpos($line, $keyword) + strlen($line), 15);
echo $name ;
$str[] = $name ;
}
} else {
// error opening file
}
fclose($file );
print_r($str) ;

Related

Find string in file and display lines number

I'm new at PHP so I'm need help to build this script.
I have a file.txt file with following lines:
aaaa 1234
bbba 1234
aaaa 1236
cccc 1234
aaaa 1238
dddd 1234
I want to find the line with string "aaaa" and print:
String "aaaa" found 3 times at lines: 1, 3, 5.
And better it can print these lines.
I tried this code:
<?
function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
$line_number = '';
if ($file_handler = fopen($filename, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search); //convert file and search string
$line = strtolower($line); //to lowercase
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number .= $i.",";
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or filename";
}
//if no match found
if(count($line_number)){
return substr($line_number, 0, -1);
}else{
return "No match found";
}
}
$output = find_line_number_by_string('file.txt', 'aaaa');
print "String(s) found in ".$output;
?>
But I dont know how to count total of strings found (3) and print each found line.
Thank in advance.
There are lots of ways to do this that produce the same final result but differ in the specifics.
Assuming that your input is not large enough that you are concerned about loading it in memory all at once, one of the most convenient approaches is to use file to read the file's contents into an array of lines, then preg_grep to filter the array and only keep the matching lines. The resulting array's keys will be line numbers and the values will be whole lines that matched, perfectly fitting your requirements.
Example:
$lines = file('file.txt');
$matches = preg_grep('/aaaa/', $lines);
echo count($matches)." matches found.\n";
foreach ($matches as $line => $contents) {
echo "Line ".($line + 1).": ".$contents."\n";
}
$str = "aaaa";
$handle = fopen("your_file.txt", "r");
if ($handle) {
echo "String '".$str."' found at lines : ";
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
echo implode(", ", $arr_lines).".";
}
UPDATE 2 :
$file = "your_file.txt";
$str = "aaaa;";
$arr = count_line_no($file, $str);
if(count($arr)>0)
{
echo "String '".$str."' found at lines : ".implode(", ", $arr).".";;
}
else
{
echo "String '".$str."' not found in file ";
}
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen("your_file.txt", "r");
if ($handle) {
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
}
return $arr_lines;
}
**Try it for solve your problam **
if(file_exists("file.txt")) // check file is exists
{
$f = fopen("file.txt", "r");
// Read line by line until end of file
$row_count = 0;
while(!feof($f))
{
$row_count += 1;
$row_data = fgets($f);
$findme = 'aaaa';
$pos = strpos($row_data, $findme);
if ($pos !== false)
{
echo "The string '$findme' was found in the string '$row_data'";
echo "<br> and line number is".$row_data;
}
else
{
echo "The string '$findme' was not found ";
}
}
fclose($f);
}

Php getting a value from a text file

I have this script, which works perfectly fine.
<?php
$lines_array = file("file.txt");
$search_string = "jummie";
foreach($lines_array as $line) {
if(strpos($line, $search_string) !== false) {
list(, $new_str) = explode(":", $line);
//$new_str = trim($new_str);
}
}
echo $new_str;
?>
If you input this file:
one: number
cheese: word
jummie: foo
bar: ar
It will return foo, for jummie (as seen in the code). Now I have modified the code, but now it does not work anymore:
<?php
$app_name = $_GET["app"];
$user_name = $_GET["user"];
$web_url = $_GET["weburl"];
$lines_array = file("accounts/userdata/". $user_name ."/". $app_name .".txt");
$search_string = "keyword";
foreach($lines_array as $line) {
if(strpos($line, $search_string) !== false) {
list(, $new_str) = explode(":", $line);
// If you don't want the space before the word bong, uncomment the following line.
//$new_str = trim($new_str);
}
}
$new_str = $keyword;
echo $keyword;
?>
Does anyone has an idea what could be the problem? Thanks!
Scratch that. You've never defined the variable $keyword which is what you are ultimately printing.
change the next-to-last line to:
$keyword = $new_str
Mayhaps you meant to do:
$search_string = $keyword;
instead of:
$search_string = "keyword";
?

How to read multibyte characters from a CSV file using PHP

I have a CSV file which contains a mixture of English and Chinese characters (it is a list of contacts exported from the Mozilla Thunderbird email program). I am trying to create a function which can extract the information from this file. It appears that function fgetcsv() does not support multibyte characters. Since I am running PHP5.2, I do not have access to str_getcsv().
Although the situation above refers to English and Chinese, I am looking for a solution which will work with any language.
Right now I have the function namecards_import_str_getcsv() as my CSV parsing function, which tries to mimic str_getcsv().
function namecards_import_str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
if (!function_exists('str_getcsv')) {
if (is_string($input) && !empty($input)) {
$output = array();
$tmp = preg_split("/".$eol."/",$input);
if (is_array($tmp) && !empty($tmp)) {
while (list($line_num, $line) = each($tmp)) {
if (preg_match("/" . $escape . $enclosure . "/", $line)) {
while ($strlen = strlen($line)) {
$pos_delimiter = strpos($line, $delimiter);
$pos_enclosure_start = strpos($line, $enclosure);
if (is_int($pos_delimiter) && is_int($pos_enclosure_start) && ($pos_enclosure_start < $pos_delimiter)) {
$enclosed_str = substr($line, 1);
$pos_enclosure_end = strpos($enclosed_str, $enclosure);
$enclosed_str = substr($enclosed_str, 0, $pos_enclosure_end);
$output[$line_num][] = $enclosed_str;
$offset = $pos_enclosure_end + 3;
}
else {
if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
$output[$line_num][] = substr($line, 0);
$offset = strlen($line);
}
else {
$output[$line_num][] = substr($line,0,$pos_delimiter);
$offset = (!empty($pos_enclosure_start) && ($pos_enclosure_start < $pos_delimiter))? $pos_enclosure_start : $pos_delimiter + 1;
}
}
$line = substr($line,$offset);
}
}
else {
$line = preg_split("/" . $delimiter . "/", $line);
/*
* Validating against pesky extra line breaks creating false rows.
*/
if (is_array($line) && !empty($line[0])) {
$output[$line_num] = $line;
}
}
}
return $output;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return str_getcsv($input);
}
}
This function is called by the following line of code:
$file = $_SESSION['namecards_csv_file'];
if (file_exists($file->uri)) {
// Load raw csv content into a handler variable.
$handle = fopen($file->uri, "r");
$cardinfo = array();
while (($data = fgets($handle)) !== FALSE) {
$data = namecards_import_str_getcsv($data);
dsm($data);
$cardinfo[] = $data[0];
}
fclose($handle);
}
else {
drupal_set_message(t('CSV file doesn\'t exist'), 'error');
}
In the array of results the strings of Chinese characters are in the correct place in the array by they appear as symbols e.g. "��".
Another method I had tried before this was to simply use fgetcsv() (See below example). But in this case the elements of the returned array were empty.
$file = $_SESSION['namecards_csv_file'];
if (file_exists($file->uri)) {
// Load raw csv content into a handler variable.
$handle = fopen($file->uri, "r");
$cardinfo = array();
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
dsm($data);
$cardinfo[] = $data;
}
fclose($handle);
}
else {
drupal_set_message(t('CSV file doesn\'t exist'), 'error');
}
In case you are interested here is the contents of the CSV file:
First Name,Last Name,Display Name,Nickname,Primary Email,Secondary Email,Screen Name,Work Phone,Home Phone,Fax Number,Pager Number,Mobile Number,Home Address,Home Address 2,Home City,Home State,Home ZipCode,Home Country,Work Address,Work Address 2,Work City,Work State,Work ZipCode,Work Country,Job Title,Department,Organization,Web Page 1,Web Page 2,Birth Year,Birth Month,Birth Day,Custom 1,Custom 2,Custom 3,Custom 4,Notes,
Ben,Gunn,Ben Gunn,Benny,ben1#asdf.com,ben2#asdf.com,,+94 (10) 11111111,+94 (10) 22222222,+94 (10) 33333333,,+94 44444444444,12 Benny Lane,,Beijing,Beijing,100028,China,13 asdfsdfs,,sdfsf,sdfsdf,134323,China,Manager,Sales,Benny Inc,,,,,,,,,,,
乔,康,乔 康,小康,,,,,,,,,,,,,,,北京市朝阳区,,,,,,,,,,,,,,,,,,,
Just writing up as an answer what was figured out in the comments:
fgetcsv is locale sensitive, so make sure to setlocale to a UTF-8 locale.

read a text file with PHP and display all text after a certain string

I have a text file with lots of text, and I want to display a part of it on the screen with PHP.
At a certain point there's string like ITEM DESCRIPTION:
What I want to get all content from this string (just after it) to the end of the file.
This is my code so far:
$file = "file.txt";
$f = fopen($file, "r");
while ($line = fgets($f, 1000))
echo $line;
:)
How about you use strstr() and file_get_contents() ?
$contents = strstr(file_get_contents('file.txt'), 'ITEM DESCRIPTION:');
# or if you don't want that string itself included:
$s = "ITEM DESCRIPTION:"; # think of newlines as well "\n", "\r\n", .. or just use trim()
$contents = substr(strstr(file_get_contents('file.txt'), $s), strlen($s));
$file = "file.txt";
$f = fopen($file, 'rb');
$found = false;
while ($line = fgets($f, 1000)) {
if ($found) {
echo $line;
continue;
}
if (strpos($line, "ITEM DESCRIPTION:") !== FALSE) {
$found = true;
}
}
What about
$file = "file.txt";
$f = fopen($file, "r");
$start = false;
while ($line = fgets($f, 1000)) {
if ($start) echo $line;
if ($line == 'ITEM DESCRIPTION') $start = true;
}
?

PHP: Splitting a string and printing

I have server output that looks like this
PLAYER_ENTERED name ipaddress username
If the string contains PLAYER_ENTERED there will always be 3 spaces within the string separating it (how can this be modified so it does this too?). I would like to print out only the ipaddress and username (last 2 sections).
How can this be done?
This is code that prints out the whole thing:
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
print "<li>$line";
}
I imagine this using explode() but I've given up trying since I hardily know how to code php.
Desired Output
username ipaddress
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
$data = explode(" ", $line); // split using the space into an array
// array index 0 = PLAYER_ENTERED
print "IP:" . $data[1]; // array index 1 = IP
print "Name: " . $data[2]; // array index 2 = name
}
}
You can use substr()to check if the first 14 characters of $line equals PLAYER_ENTERED and then you use list() and explode() to extract the data from the line.
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while(($line = fgets($f)) !== FALSE)
{
if(substr($line, 0, 14) == 'PLAYER_ENTERED'){
list($event, $name, $ip, $username) = explode($string); // here they come!
echo 'Name: ' . $name . ', ip: ' . $ip . ', username: ' . $username;
}
}
try this ...
<?
$str = "PLAYER_ENTERED name 108.21.131.56 username";
if ( preg_match( "~^(.+)\s+(.+)\s+([\d\.]+)\s+(.+)$~msi", $str, $vv ))
echo $vv[3] . " and " .$vv[4] ;
else "N/A";
?>
IMHO Perl regexp - is the right Way to parse strings ...
One way would be:
$tokens = explode(' ', $line);
if (count($tokens) == 4 && $tokens[2] == $q) {
printf('IP: %s Username: %s', $tokens[2], $tokens[3]);
}
<?php
$str = 'PLAYER_ENTERED name 108.21.131.56 username';
$data = explode(" ", $str )
print_r($data)
?>

Categories