Getting File Name Details from Image File - php

I am looking for a way to grab details from a file name to insert it into my database. My issue is that the file name is always a bit different, even if it has a pattern.
Examples:
arizona-911545_1920.jpg
bass-guitar-913092_1280.jpg
eiffel-tower-905039_1280.jpg
new-york-city-78181_1920.jpg
The first part is always what the image is about, for example arizona, bass guitar, eiffel tower, new york city followed by a unique id and the width of the image.
What I am after would be extracting:
name id and width
So if I run for example getInfo('arizona-911545_1920.jpg');
it would return something like
$extractedname
$extractedid
$extractedwidth
so I could easily save this in my mysql database like
INSERT into images VALUES ('$extractedname','$extractedid','$extractedwidth')
What bothers me most is that image names can be longer, for example new-york-city-bank or even new-york-city-bank-window so I need a safe method to get the name, no matter how long it would be.
I do know how to replace the - between the name, that's not an issue. I am really just searching for a way to extract the details I mentioned above.
I would appreciate it if someone could enlighten me on how to solve this.
Thanks :)

One of the simplest way in this case is to use regexp, for example:
preg_match('/^(\D+)-(\d+)_(\d+)/', $filename, $matches);
// $matches[1] - name
// $matches[2] - id
// $matches[3] - width

This is the main Idea.
Let's pick a file first.
Filename will be "bass-guitar-913092_1280.jpg"
First of all we will Split this with explode, to dot( . ) in variable $Temp
This will give us an Array of bass-guitar-913092_1280 and jpg
We will choose to have the first Item of the array to continue since is the name we are interested in so we will get it with $Temp[0]
After this we will Split it Again this time to ( _ ).
Now we will have an array of bass-guitar-913092 and 1280
The Second value of the Array is what We need so we will pick it with $Temp[1]
The Last part is simple as the others, We will now Split the file name $Temp[0] with ( - ) We will get the Last value of it which is the id $Temp[count($Temp)-1] and we will remove this from the array list, and Connect everything else with implode and the delimeter we want
Now we can use also the Function ucwords to Capitalize every first letter of each word on the main name.
In the following code, there are 2 ways of getting the name, one with lowercase letters, and one with uppercase first letters of each word, uncomment what you want.
Edited Code as a Function
<?php
function ExtractFileInfo($fileName) {
$Temp = explode(".",$fileName);
$Temp = explode("_",$Temp[0]);
$width = $Temp[1];
$Temp = explode("-",$Temp[0]);
$id = $Temp[count($Temp)-1];
unset($Temp[count($Temp-1)]);
// If you want to have the name with lowercase letters Uncomment the Following:
//$name = implode(" ",$Temp);
// If you Want to Capitalize every first letter of the name Uncomment the Following:
//$name = ucwords(implode(" ",$Temp));
return array($name,$id,$width);
}
?>
This will return an Array of 3 Elements Name, Id and Width

Extracting the data you are looking for would be best via a regex pattern like the following:
(.+)-(\d+_(\d+))
Example here: https://regex101.com/r/oM5bS8/2
preg_match('(.+)-(\d+_(\d+))',"<filename>", $matches);
$extractedname = $matches[1];
$extractedid = $matches[2];
$extractedwidth = $matches[3];
EDIT - Just reread the question and you are looking for extraction techniques not how to post the image from a page to your backend. I will leave this here for reference.
When you post files via a form in html to a PHP backend there are few items that are needed.
1) You need to ensure that your form type is multi-part so that it knows to pass the files along.
<form enctype="multipart/form-data">
2) Your php backend needs to iterate over the files and save them accordingly.
Here is a sample of how to iterate over the files that are being submitted.
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
if (!$n) continue;
echo "File: $n ($s bytes)";
}

Related

Open a text file, search for integer and then display text after a character

I have a multi-line text file that contains a number and url
59=folder/image.png
63=folder/image2.png
etc...
I want to search the file for "59" and then echo the url in img src
If the text file doesn't contain "59", I want to echo an alternative image
There's a problem because the png filename is also an integer
I have tried this with code that doesn't make sense, as pointed out by a user below.
You say you want to "search the file for 59", but surely actually you only want to search the beginning of the line. That would solve the issue with having numbers in the filename.
Your code so far doesn't make a lot of sense, it isn't searching for 59 at all, anywhere in the text.
This will do the job correctly:
$search_ID = "59"; //Note: this is now a string, so we can check its length, and match that in the file
$data = file_get_contents('text_file.txt'); //$contents was redundant, just start by calling it $data
$result = "";
if (substr($data, 0, strlen($search_ID)) == $search_ID)
{
$result = substr($data, strpos($data, "=")+1);
}
else
{
$result = "something else"; //replace this with whatever alternative output you need
}
Demo: http://sandbox.onlinephpfunctions.com/code/fb413cd66670001fe6e665b9e10b55285d1440b1
P.S. this code assumes the file only ever has one line. It wasn't quite clear from your question where there was the potential for it to have multiple lines in the same format, or not.

Searching a text file and displaying a part of the String. (PHP)

So I want to search a text file which contains a list of suburbs with names and postcodes. Depending on the the postcode given I want to display the suburb. I know I'm suppose to loop through the text file but have no idea how to actually search for exact value in the line and then display a different part of that same line. I know that I can use the explode function and get the part of the string I want but what I don't know how to do is loop through the file and finding the exact line of it.
Any Help on this is most Appreciated !
Thanks !
Since you didn't provide any example of what you have tried so far, this may not completely match what you are doing.
Assuming a file suburbs.txt with contents like:
Somewhere,12345
Somewhere Else,12346
This Place,12347
There,12348
You could do the following to loop through the entries:
$zipCode = '12346';
$lines = file('/path/to/suburbs.txt');
foreach ( $lines as $line )
{
$fields = explode( ',', $line );
if ( $fields[1] == $zipCode )
{
echo "Your suburb is: " . $fields[0];
break;
}
}
file() loads a file into an array. This is what allows you to loop through using foreach(). There are other methods of doing this as well, but this should help you move in the right direction.

How to show 1 element of array dynamically with php?

in "file.txt" i have some numbers like 1234,123456,12345678 etc.
so i was wondering how i can get dynamically just one element, for example echo just 12345,then echo 123456, but one by one ???when user comes i want to show him one element,and then next time i want to show another element on the page, it would be good also if i could erase elements that i have echo...When i manually enter position it works... Please help...
I have a following code:
function test($n){
$file=file_get_contents("file.txt");
$array = explode(",", $file);
return print_r($array[$n]);
};
The solution will need deleting the number on your filesystem or marking it as already showed either on the filesystem or on the database, after the number gets echoed.
Shuffling the numbers or generating a random index will never quite be full proof since the same number could be shown again.
First of all, this is usually a terrible way of doing this.
It's much better to use a database, for example.
But you could do the following:
<?php
function getRandomNumber() {
// retrieve and parse the numbers
$numbers = file_get_contents('file.txt');
$numbers = explode(',' $numbers);
// select a random index
$randomIndex = array_rand($numbers);
// get the chosen number
$randomNumber = $numbers[$randomIndex];
// remove it from array
unset($numbers[$randomIndex]);
// save updated file
file_put_contents('file.txt', implode(',', $numbers));
return $randomNumber;
}

Preg-Match-All - Synonym File

I am writing a php script that will parse through a file, (synonyms.dat), and coordinate a list of synonyms with their parent word, for about 150k words.
Example from file:
1|2
(adj)|one|i|ane|cardinal
(noun)|one|I|ace|single|unity|digit|figure
1-dodecanol|1
(noun)|lauryl alcohol|alcohol
1-hitter|1
(noun)|one-hitter|baseball|baseball game|ball
10|2
(adj)|ten|x|cardinal
(noun)|ten|X|tenner|decade|large integer
100|2
(adj)|hundred|a hundred|one hundred|c|cardinal
(noun)|hundred|C|century|one C|centred|large integer
1000|2
(adj)|thousand|a thousand|one thousand|m|k|cardinal
(noun)|thousand|one thousand|M|K|chiliad|G|grand|thou|yard|large integer
**10000|1
(noun)|ten thousand|myriad|large**
In the example above I want to link ten thousand, myriad, large to the word 1000.
I have tried various method of reading the .dat file into memory using file_get_contents and then exploding the file at \n, and using various array search techniques to find the 'parent' word and it's synonyms. However, this is extremely slow, and more often then not crashes my web server.
I believe what I need to do is use preg_match_all to explode the string, and then just iterate over the string, inserting into my database where appropriate.
$contents = file_get_contents($page);
preg_match_all("/([^\s]+)\|[0-9].*/",$contents,$out, PREG_SET_ORDER);
This matches each
1|2
1-dodecanol|1
1-hitter|1
But I don't know how to link the fields in between each match, IE the synonyms themselves.
This script is intended to be run once, to get all the information into my database appropriately. For those interested, I have a database 'synonym_index' which holds a unique id of each word, as well as the word. Then another table 'synonym_listing' which contains a 'word_id' column and a 'synomym_id' column where each column is a foreign key to synonym_index. There can be multiple synonym_id's to each word_id.
Your help is greatly appreciated!
You can use explode() to split each line into fields. (Or, depending on the precise format of the input, fgetcsv() might be a better choice.)
Illustrative example, which will almost certainly need adjustment for your specific use case and data format:
$infile = fopen('synonyms.dat', 'r');
while (!feof($infile)) {
$line = rtrim(fgets($infile), "\r\n");
if ( $line === '' ) {
continue;
}
// Line follows the format HEAD_WORD|NUMBER_OF_SYNONYM_LINES
list($headWord, $n) = explode('|', $line);
$synonyms = array();
// For each synonym line...
while ( $n-- ) {
$line = rtrim(fgets($infile), "\r\n");
$fields = explode('|', $line);
$partOfSpeech = substr(array_shift($fields), 1, -1);
$synonyms[$partOfSpeech] = $fields;
}
// Now here, when $headWord is '**10000', $synonyms should be array(
// 'noun' => array('ten thousand', 'myriad', 'large**')
// )
}
Wow, for this type of functionality you have databases with tables and indices.
PHP is to serve a request/response, not to read a big file into memory. I advise you to put the data in a database. That will be much faster - and it is made for it.

php check if file exist: check only portion

in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

Categories