Php line count files

Всего строк PHP_Count во всех файлах в данной папке

Просто хотел подсчитать общее количество строк из всех файлов из папки. следующая функция php помогает мне подсчитать число строк только для определенного файла. просто интересно, каков путь к общему количеству строк из папки.

То же, что и выше (ответ salathe), за исключением того, что он печатает количество строк (теперь в php7), а не пучок сообщений об ошибках.

$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__)); $lines = 0; foreach ($files as $fileinfo) < if (!$fileinfo->isFile()) < continue; >$read = $fileinfo->openFile(); $read->setFlags(SplFileObject::READ_AHEAD); $lines += iterator_count($read) - 1; // -1 gives the same number as "wc -l" > echo ("Found :$lines"); 

Вы можете перебирать каталог и подсчитывать каждый файл и суммировать их все. И вы используете функцию file() , которая будет загружать весь контент в память, если файл очень большой, ваш php-скрипт достигнет предела памяти вашей конфигурации.

Читайте также:  Java заменить все символы

Если вы можете использовать внешнюю команду, есть решение с одной строкой. (Если вы используете окна, просто опустите его.)

$total = system("find $dir_path -type f -exec wc -l <> \; | awk ' END'"); 

Что-то вроде этого возможно:

 > closedir($handle); > var_dump($line_count); ?> 

Проверьте стандартную библиотеку PHP (она же SPL) для DirectoryIterator:

$dir = new DirectoryIterator('/path/to/dir'); foreach($dir as $file )

(FYI есть недокументированная функция, называемая iterator_count (), но, вероятно, лучше не полагаться на нее, пока я себе представляю. И вам нужно будет отфильтровать невидимые вещи, как и все равно.)

или попробуйте следующее:

$directory = "../images/team/harry/"; if (glob($directory . "*.jpg") != false) < $filecount = count(glob($directory . "*.jpg")); echo $filecount; >else

Очень простой пример подсчета строк может выглядеть примерно так: это дает те же цифры, что и ответ xdazz .

isFile()) < continue; >$files++; $read = $fileinfo->openFile(); $read->setFlags(SplFileObject::READ_AHEAD); $lines += iterator_count($read) - 1; // -1 gives the same number as "wc -l" > printf("Found %d lines in %d files.", $lines, $files); 
  • RecursiveDirectoryIterator
  • SplFileInfo
  • SplFileObject
  • RecursiveIteratorIterator
  • iterator_count()

Источник

Count Lines in File in PHP

To count the number of lines in a file in PHP, you can use one of the following approaches:

Use the file() function

This function reads the entire file into an array, with each line of the file as an element in the array. Then, use the count() function to count the number of elements in the array.

Here is an example of how to count lines in file in PHP using the file() method.

Note that this approach counts empty lines that exist within the file.

This code assumes that you have file.txt in current folder. You can provide relative path or absolute path based on the preference.

Use the file_get_contents() function

Using the FILE_IGNORE_NEW_LINES flag

Here, we can count lines in a file using the file_get_contents() function with the FILE_IGNORE_NEW_LINES flag. This function reads the entire file into a string, ignoring newline characters. Then, use the substr_count() function to count the number of newline characters in the string.

The FILE_IGNORE_NEW_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Using the FILE_SKIP_EMPTY_LINES flag

Here we make use of the file_get_contents() function alongside the FILE_SKIP_EMPTY_LINES flag to count lines in file.

This function reads the entire file into a string, skipping empty lines. Then, use the substr_count() function to count the number of newline characters in the string.

Here is an example script on how to use the function.

The FILE_SKIP_EMPTY_LINES ignores the newlines that are empty, and simply focuses on lines with characters.

Use the fopen() and fgets() functions

Another approach we can take is count lines in file using a loop. This approach makes use of the fopen() and fgets() function to reads the file line by line, incrementing a counter variable for each line.

Note that this approach counts empty lines that exist within the file.

fopen() method with r is used to open file in read mode.

fgets() method is used to get line from file pointer in PHP.

That’s all about how to count lines in file in PHP.

Was this post helpful?

Share this

Author

Remove Last Character from String in PHP

Table of ContentsUse the substr() functionUse the rtrim() functionUse the mb_substr() functionUse the preg_replace() functionUse the str_split() and array_pop() function This article explains different ways to remove the last character from a string in PHP Use the substr() function To remove last character from String in PHP, use of the substr() function and pass a […]

Check if Variable is Array in PHP

Table of ContentsUsing the is_array() functionUsing the gettype() functionUsing the typesetting syntax Using the is_array() function To check if variable is array in PHP, use is_array() function. The is_array() function is a built-in function in PHP that takes a variable as an argument and returns a Boolean value indicating whether the variable is an array. […]

Split String by Comma in PHP

Table of ContentsUse the explode() functionUse the str_getcsv() functionUse the preg_split() functionUse the mb_split() function This article explains how to split a string by comma in PHP using different approaches. Use the explode() function To split string by comma, we can make use of the explode function. This function splits the string by the specified […]

Format Number to 2 Decimal Places in PHP

Table of ContentsUsing the round() functionUsing the number_format() functionUse sprintf() functionUse the floatval and number_format function Using the round() function To format a number to 2 decimal places in PHP, you can use the round() function and pass the number and 2 as arguments to the round() function. Here is an example of how to […]

Check if Array is Empty in PHP

Table of ContentsUse empty() functionUse count() functionUse array_key_exists() functionUse array_filter() functionUse array_reduce() function Use empty() function To check if an array is empty in PHP, you can use the empty() function. This function accepts an array as its argument, and it returns true if the array is empty and false if the array is not […]

Replace Space with Underscore in PHP

Table of ContentsUsing str_replace() MethodUsing preg_replace() Method Using str_replace() Method Use the str_replace() function to replace with underscore in PHP, for example: str_replace(» » , «_», $str). str_replaces() returns new String with old character space( ) replaced by underscore(_) [crayon-64bdc30d7ac55082164352/] [crayon-64bdc30d7ac59300722632/] We used str_replace() to replace space with underscore in PHP. str_replace() replaces all instances […]

Источник

PHP Exercises : Count number of lines in a file

Write a PHP script to count number of lines in a file.

Note : Store a text file name into a variable and count the number of lines of text it has.

Sample Solution:

There are 5 lines in a6924e70-5a4c-11e7-b47b-99347412a245.php

Flowchart: Count number of lines in a file

basename() function: The basename(path,suffix) function is used to get the filename from a path.

count() function: The count() function is used to count the elements of an array or the properties of an object.

Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

What is the difference between public, private, and protected?

  • public scope to make that property/method available from anywhere, other classes and instances of the object.
  • private scope when you want your property/method to be visible in its own class only.
  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to count the number of lines in a text file using PHP

Hello, I have posted several posts on working with a text file in PHP. Some of those were really helpful to the learners. Like
How to read a particular line from a text file in PHP
Fetching Text Data From a Text File Using PHP
Save HTML Form Data in a (.txt) Text File in PHP
But here in this post, I am going to show you How to count the number of lines in a text file using PHP.

Count the number of lines in a text file using PHP

To count the number of lines in a text file in PHP we need to use these below PHP function:

To get a better Idea you may read this post, this post is very similar to this one How to read a particular line from a text file in PHP You just need to extend a single line.

So let’s create a text file first.

Hello I am from line no 1 Hi I am from line no 2 hello again I am from line no 3 Hey I am from line no 4

Now you need to count the number of lines in this text file. Here we have 4 lines.

Save this file with any filename. Here I am going to save it as mytextfile.txt

PHP program to count the number of lines in a text file :

This above program will give you the number of lines in a text file.

Special note: The file() function actually returns an array. So here $all_lines variable holds the whole text file as an array. count() function will count the number of elements in the array.

Источник

Как подсчитать количество строк в файле PHP?

Возможно, Вы уже столкнулись с задачей подсчёта общего количества строк в файле. Неважно, нужно подсчитать количество служебных записей в файле, узнать количество строк htaccess или записей txt-файла, хранящего в себе какие-либо данные. Указанные ниже способы решения подойдут для каждого случая.

Создадим функцию для подсчёта количество строк в файле PHP

Создаваемая функция будет использовать две встроенные:

1. file() в качестве аргумента принимает файл или путь к нему, а возвращает массив строк
2. count() подсчитывает количество элементов массива.

Теперь переходим к созданию файла с самой функцией. В корневой директории (вы можете на своё усмотрение выбрать другую) создаём отдельную папку include. В ней создадим файл будущей функции и назовём его functions.php. Далее вставляем в него указанный ниже код.

Код PHP (файл functions.php)

  
function lines($file)
<
// в начале ищем сам файл. Может быть, путь к нему был некорректно указан
if(!file_exists($file))exit("Файл не найден");

// рассмотрим файл как массив
$file_arr = file($file);

// подсчитываем количество строк в массиве
$lines = count($file_arr);

// вывод результата работы функции
return $lines;
>

echo lines("index.php"); // выводим число - количество строк в файле index.php

?>

Итак, файл с функцией готов. В корневой директории (папке) можем уже создать рабочий файл с любым названием (в примере его назвал example.php), а в нём данную функцию будем подключать следующим образом.

Код PHP (файл example.php)

  
// здесь указываем путь к файлу с функцией
include_once "include/functions.php"; // или "functions.php" если функция в той же папке, что и рабочий файл exemaple.php

// в переменную $count_lines сохраняем количество строк (число)
$count_lines = lines("index.php");

// выводим результат работы функции подсчёта строк
echo "Строк в файле: ".$count_lines;

?>

В результате отобразит примерно следующий текст

Строк в файле: 52
Можно рассмотреть пример короче без создания функции. В нём уже не будет никакой проверки на наличие файла

Код PHP (вставляете в любой файл php)

 $file = "file.txt"; // указываем сам файл и путь к нему 
$lines = count(file($file)); // высчитываем количество строк
echo "В файле $file количество строк $lines"; // отображаем результат
?>

В файле file.txt количество строк 20
Спасибо за внимание!

Источник

Оцените статью