Removing some strings in a word in PHP within an array - php

I am have retrieved all the file contents from a directory. It prints the file contents name from an array. However I want only a portion of the file content name. Any idea how can I achieve this? I have tried using the following:
The file contents from the directory has format: pdb101m.ent.gz , pdb102l.ent.gz
I want to retrieve only the 101m and 102l
<?php
$dir = "C:/Users/Desktop/EAD/PDB/";
$files = array();
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
foreach($files as $ex){
echo str_replace('pdb.ent.gz', ' ', $ex). '<br>';
}
?>
Please help. Grateful.

Use substr() function:
echo substr('pdb101m.ent.gz',3,4); // Outputs: 101m
echo substr('pdb102l.ent.gz',3,4); // Outputs: 102l
So:
foreach($files as $ex){
echo substr($ex, 3,4). '<br>';
}
Edit: Update my answer attending the OP new request:
So in your query you should use:
foreach ($files as $ex) {
$search = substr($ex, 3, 4);
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 6';
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$pdb[] = $row['pdb_code'];
}
}

If it's always pdb at the beggining and .ent.gz at the end you can do simply:
echo substr('pdb101m.ent.gz',3,-7);
Negative value of third parameter in substr() means
that many characters will be omitted from the end of string

Related

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

Conditional regex php

I'm facing some problem with php regex but after many researches (conditional regex, subpattern regex), I still can't solve it.
I have a folder that contains many images and based on variable value I have to go to that folder and select all images that match the value.
e.g: In my folder I have 3 images:
p102.jpg ; p1020.jpg ; p102_1.jpg;
I only want the regex to select :
p102.jpg ; p102_1.jpg
but with the regex below It selects all 3 images.
$image_to_find = 102;
$path = "[^\d]*.*/"
$test = "/^[a-zA-Z]?$image_to_find".$path;
foreach(glob($file_directory) as $file){
if(preg_match($test, $file)){
match[]= $file;
}
}
I also try:
$path = "(?:\_[0-9]?).*/"; (it selects only p102_1.jpg)
Can you help me to figure it out. thanks
(sorry for the english)
You can avoid the foreach loop if you use the glob pattern:
$num = 102;
$result = glob($path . '[a-zA-Z]' . $num . '[._]*');
Note: if you need to allow several different formats, you can use array_merge and several glob patterns: array_merge(glob(...), glob(...));
If you want the first letter optional:
$result = array_merge(
glob($path . $num . '[._]*jpg'),
glob($path . '[a-zA-Z]' . $num . '[._]*jpg')
);
or better, use the brace option:
$result = glob($path . '{[a-zA-Z],}' . $num . '[._]*jpg', GLOB_BRACE);
That stays a better alternative than the combo "foreach/preg_match" (or preg_grep) if filenames are not too complicated.
With preg_grep:
$pattern = '~(?:^|/)[a-z]?' . $num . '(?:_\d+)?\.jpg$~i';
$result = preg_grep($pattern, glob($path . '*' . $num . '*.jpg'));
Try this:
/p102[_\.]\d*\.?jpg/g
https://regex101.com/r/hM4oE0/1
Where p102 should be your 'image_to_find' var.
Not tested, should work.
$find = 102;
$pattern = "/p". $find ."(?:_\d+)?\.jpg/";
$list = array();
foreach (glob($file_directory) as $file)
{
if (preg_match($pattern, $file))
{
$list[] = $file;
}
}
regex: http://regexr.com/3bp29
Tested and working:
<?php
$image_to_find = 102;
$pattern = '[a-zA-Z]' . $image_to_find . '[._]*';
$path = '/your_folder/your_subfolder/';
$file_directory = glob($path . $pattern );
echo '<pre>';
var_dump($file_directory);
echo '</pre>';
exit();
I hope this helps!

php count files from multiple folders and echo total

I have a php code that will display the amount of files that i have in a folder.
Code: This will echo this on my page, "There are a total of 119 Articles"
$directory = "../health/";
if (glob($directory . "*.php") != false) /* change php to the file you require either html php jpg png. */ {
$filecount = count(glob($directory . "*.php")); /* change php to the file you require either html php jpg png. */
echo "<p>There are a total of";
echo " $filecount ";
echo "Articles</p>";
} else {
echo 0;
}
Question:
I am wanting to count the files from 27 or more folders and echo the total amount of files.
Is there away i can add a list of folders to open such as:
$directory = "../health/","../food/","../sport/";
then it will count all the files and display the total "There are a total of 394 Articles"
Thanks
Yes you can:
glob('../{health,food,sport}/*.php', GLOB_BRACE);
Undoubtedly, this is less efficient than clover's answer:
$count = 0;
$dirs = array("../health/","../food/","../sport/");
foreach($dirs as $dir){
if($files = glob($dir."*.php")){
$count += count($files);
}
}
echo "There are a total of $count Articles";
A simple answer is to just use an array and a loop. It is something you could have figured out yourself.
$directories = array('../health/', '../food/', '../sport/');
$count = 0;
foreach ($directories as $dir) {
$files = glob("{$dir}*.php") ?: array();
$count += count($files);
}
echo "<p>There are a total of {$count} articles</p>";
But #clover's answer is better.
As usual, it's often much better to divide your problem. E.g.:
Obtain the files (See glob).
Count the files of a glob result (Write a function that takes care of two the FALSE and Array cases.).
Do the output (don't do the output inside the other code, do it at the end, use variables (as you already do, just separate the output)).
Some Example Code:
/**
* #param array|FALSE $mixed
* #return int
* #throws InvalidArgumentException
*/
function array_count($mixed) {
if (false === $mixed) {
return 0;
}
if (!is_array($mixed)) {
throw new InvalidArgumentException('Parameter must be FALSE or an array.');
}
return count($mixed);
}
$directories = array("health", "food", "string");
$pattern = sprintf('../{%s}/*.php', implode(',', $directories));
$files = glob($pattern, GLOB_BRACE);
$filecount = array_count($files);
echo "<p>There are a total of ", $filecount, " Article(s)</p>";
You could use the opendir command explained here:
http://www.php.net/manual/en/function.opendir.php
combined with the example shown on previous link:
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Basically opening the folder you first go through and in a loop count every singel item that is not a folder.
Edit:
Seems like someone has given a simpler solution than this.

Using glob to filename parameters

Here's what I need, I have files: "page-Home1.php", "page-Contact2.php".
Yes I understand they don't have beautiful names but that's not what I'm worrying about right now, what I need is for glob to echo the files in order by 1,2,3 etc..
I currently have:
<?php
foreach (glob("page-*") as $filename) {
$result = str_replace("page-","", $filename);
$result = str_replace(".php","", $result);
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>
Though that only spits them out in a random order, I need it to number order.... Any ideas?
$files = glob(dirname(__FILE__).'/page-*.php');
foreach ($files as $file) {
$result[preg_replace('#[^0-9]#','', $file)]['file'] = $file;
$result[preg_replace('#[^0-9]#','', $file)]['name'] = str_replace(array("page-", ".php"), array('', ''), $file);;
}
sort($result);
foreach($result as $data) {
echo $data['file'].' -> '.$data['name'].'<br>';
}
Sort your array before iterating over it.

Getting word count for all files within a folder

I need to find word count for all of the files within a folder.
Here is the code I've come up with so far:
$f="../mts/sites/default/files/test.doc";
// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";
This will count the words within a single file, how would I go about counting the words for all files within a given folder?
how about
$array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
$result = array();
foreach($array as $f ){
$result[$f] = str_word_count(file_get_contents($f));
}
and using the dir
if ($handle = opendir('/path/to/files')) {
$result = array();
echo "Directory handle: $handle\n";
echo "Files:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..')
continue;
$result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file));
echo "This file {$file} have {$result[$file]} words";
}
closedir($handle);
}
Lavanya, you can consult the manual of readdir, file_get_contents.
Assuming the doc files are plaintext and don't contain additional markup, you can use the following script to count all of the words in all of the files:
<?php
$dirname = '/path/to/file/';
$files = glob($dirname.'*');
$total = 0;
foreach($files as $path) {
$count = str_word_count(file_get_contents($path));
print "\n$path has $count words\n";
$total += $count;
}
print "Total words: $total\n\n";
?>
If you are using *nux than you can use system('cat /tmp/* | wc -w')
You can use $words = str_word_count(file_get_contents($filepath)) to get the word count of a text file, however this won't work for word docs. You'll need to find a library or external program that can read the .doc file format.

Categories