PHP substring extrac and calulate - php

I'm using to show exif data of a picture.
this is the code
<?php
$filename = "http://www.rallyfun.net/images/20140921231511_img_7369.jpg";
$exif = exif_read_data($filename, 0, true);
echo "Exposure: " . $exif["EXIF"]["ExposureTime"] . " sec.<br />";
echo "F: " . $exif["EXIF"]["FNumber"] . "<br />";
echo "ISO: " . $exif["EXIF"]["ISOSpeedRatings"] . "<br />";
?>
this is the result:
Exposure: 1/6400 sec.
F: 63/10 sec.
ISO: 1000
the result is ok except for the aperture: it must be displayed as (in this case) 6.3 so i need to divide the first number (63) with the number after the "/" (10).
how?

U can use explode for this.
$tmp = explode('/', str_replace(' sec.', '', $exif["EXIF"]["FNumber"]));
echo "F: " . ($tmp[0]/$tmp[1]) . "sec<br />";

You can use this code to display aperture:
preg_match('/([0-9]+)\/([0-9]+)/',$exif["EXIF"]["FNumber"],$m);
if($m[1] && $m[2])
{
$newaperture = $m[1]/$m[2];
echo $newaperture;
}

Try the following :
$n = $exif["EXIF"]["FNumber"];
$whole = floor($n); // 63
$fraction = $n - $whole; // .10
$result=$whole/$fraction;

Related

Compairing html string to hex string with php

I am trying to compare two strings. When compared they are unequal to the computer. But to the human eye the strings appear to be the same.
When I run a test to check the bin2hex with php they are clearly unequal. Some how a set of double quotes is be read as html. Here are some examples:
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
The code above will out put the following information.
Checking: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI LAYERED STEEL 4.585"
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e35383522
testing 3630 3632 With: 1 PAIR OF BBC HEAD GASKET GASKETS MULTI
LAYERED STEEL 4.585″
312050414952204f46204242432048454144204741534b4554204741534b455453204d554c5449204c41594552454420535445454c20342e3538352623383234333b
false
I am kinda lost on what to do... Any help would be greatly appreciated. Below is the rest of the code so you can get a total feel for what I'm trying to accomplish.
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
foreach($_SESSION['pushIdArrayQuery'] as $key => $value)
{
$string1 = strlen(html_entity_decode($_SESSION['pageTitleArray'][$b]));
$string2 = strlen(html_entity_decode($value));
echo 'Checking: ' . $_SESSION['pageTitleArray'][$b] . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'testing ' . $string1 . " = "bin2hex($string1) . " " . bin2hex($string2);
echo '<br>';
echo 'With: ' . $value . " " . bin2hex($value);
if(trim($_SESSION['pageTitleArray'][$b]) == trim($value))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
}
}
You have two different types of quotations mark (" on the first string and ″ on the second one).
To human eyes they seems similar but they are complete different characters to PHP.
This is how I fixed the problem. Notice, I removed any html attributes with the html_entity_decode() function. Then, from there I was able to strip away all other special characters by using preg_replace() and compare the results.
//Loop through all the page titles from the directories
for($b = 0; $b < count($_SESSION['pageTitleArray']); $b++)
{
//Loop through the page titles gathered from the database
foreach($_SESSION['pushTitleArrayQuery'] as $key => $value)
{
//use html decode to remove the quotes with ENT_NOQUOTES
$removeHtml = html_entity_decode($value, ENT_NOQUOTES);
//Test to make sure the encoding are the same for both variables.
$detectEncoding = mb_detect_encoding($value, "auto");
//remove all non alphanumeric variables in the first string.
$string1 = preg_replace("/[^a-zA-Z0-9]/", "", $_SESSION['pageTitleArray'][$b]);
//remove all non alphanumeric variables in the second string.
$string2 = preg_replace("/[^a-zA-Z0-9]/", "", $removeHtml);
//Print out to see what the results look like from decode and encoding functions
echo 'Testing the removal of html quotes: ' . $removeHtml . ' Encoding: ' . $detectEncoding;
echo '<br>';
//Show what variables are being compaired.
echo 'Checking: ' . $string1 . " " . bin2hex($_SESSION['pageTitleArray'][$b]);
echo '<br>';
echo 'With: ' . $string2 . " " . bin2hex($value);
//If statement to check if the to strings match.
if(trim($string1) === trim($string2))
{
echo '<br>';
echo '<h1>Success</h1>';
echo '<br>';
echo '<b>Key: </b>' . $key;
echo '<br>';
echo 'Page Title: ' . $_SESSION['pushTitleArrayQuery'][$key];
echo '<br>';
echo 'Page Id: ' . $_SESSION['pushIdArrayQuery'][$key];
echo '<br> ';
}
else {
echo '<br>';
echo 'false';
echo '<br>';
}
echo '<br>';
}
}

How to find a substring of a string in an array PHP

If you look at many of my questions, you will see that sometimes I don't ask the best questions or I am in such a rush that I don't see the answer that is right in front of me the whole time. If this is another one of those questions, please be kind as some other people haven't been the nicest. Now onto the question.
I have been in the process of creating a file listing viewer type thing for the past week or so. At this point, its all great but I needed to add a search function. I did so by using array_search(). The only problem is that this function requires you to put in the EXACT name of the file rather than part of it.
Here is the problem. I have tried numerous solutions, and to be frank, my PHP skills aren't the most professional. I have tried for array_filters and for loops with strpos. Nothing at this point works. My code is below:
<?php
//error_reporting(0);
//ini_set('display_errors', 0);
//$dir = $_SERVER["DOCUMENT_ROOT"] . '/';
$dir = getcwd();
$files = $files = array_slice(scandir($dir), 2);
$number = count($files);
sort($files);
$images = array();
$an = count($images);
$query = $_GET['q'];
$searchimages = array();
$san = count($searchimages);
$r = array();
if ($query) {
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
if ($r != null) {
if (substr($files[$r], -5) == ".jpeg" || substr($files[$r], -4) == ".png" || substr($files[$r], -4) == ".jpg" || substr($files[$r], -4) == ".gif") {
$searchimages[$san++] = $files[$r];
echo "<a href='#" . $files[$r] . "'>" . $files[$r] . "</a><br>";
} else {
echo "<a href='" . $files[$r] . "'>" . $files[$r] . "</a><br>";
}
for ($z = 0; $z <= $san; $z++)
echo "<a name='" . $searchimages[$z] . "'>" . "<a href='" . $searchimages[$z] . "' target='_blank'>" . "<img src='" . $searchimages[$z] . "'>" . "</img></a>";
} else {
echo "No results found. Please try a different search" . "<br>";
}
} else {
for ($x = 0; $x <= $number; $x++) {
if (substr($files[$x], -5) == ".jpeg" || substr($files[$x], -4) == ".png" || substr($files[$x], -4) == ".jpg" || substr($files[$x], -4) == ".gif") {
$images[$an++] = $files[$x];
echo "<a href='#" . $files[$x] . "'>" . $files[$x] . "</a><br>";
} else {
echo "<a href='" . $files[$x] . "'>" . $files[$x] . "</a><br>";
}
}
for ($y = 0; $y <= $an; $y++) {
echo "<a name='" . $images[$y] . "'>" . "<a href='" . $images[$y] . "' target='_blank'>" . "<img src='" . $images[$y] . "'>" . "</img></a>";
}
}
?>
Currently there are over 2,000 files and they have all sorts of random characters in them. These characters range from dashes to exclamation marks to letters and numbers as well as periods and many more. I don't have control over these file names and they have to stay exactly the same.
If you look at the code, I first get all the file names and store them in an array,
$files
Then I check if the search parameter is supplied in the url,
?q=insert-search-terms-here
After that, if it is supplied, I will search for it (this is where the problem is). If it isn't supplied, I simply get the file names from the array and check if they are an image. If they are, I print them all out at the bottom of the page in the form of thumbnails and make their link at the top a page link that scrolls you down to the location of the image. If it isn't an image, it takes you directly to the file. Note that the thumbnails are links to the actual image.
What is supposed to happen when it searches is that basically does what it would do if it weren't searching, but it limits itself to files that contain the string "foobar" for example.
When it searches but doesn't find anything, it prints out that it didn't find anything and that the user should search again.
If anyone could help with this, it would be greatly appreciated. Like I said at the beginning, please be kind if its a dumb mistake.
Best Regards,
Emanuel
EDIT:
This article now obviously has an answer and for those finding this article on Google or what have you, I want you to read the comments in the answer post as well as the answer as they provide KEY information!!
You may want to use preg_grep. Replace this:
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
with this:
$r = preg_grep('/\Q' . $query . '\E/', $files);
Example:
$files = array(
'foo.bar',
'barfoo.baz',
'baz.fez',
'quantum-physics.ftw',
);
$query = 'foo';
$r = preg_grep('/\Q' . $query . '\E/', $files);
print_r($r);
Output:
Array
(
[0] => foo.bar
[1] => barfoo.baz
)
The preg_match below can be read "match any string ending with a dot followed by jpeg, png, jpg or gif" (the dollar sign can be translated into "end of the string").
if ($query) {
$r = preg_grep('/\Q' . $query . '\E/', $files);
if ($r != null) {
foreach($r as $filename) {
if (preg_match('/\.(jpeg|png|jpg|gif)$/', $filename)) {
// File is an image
echo "$filename is an image<br/>";
// Do stuff ...
} else {
// File is not an image
echo "$filename is NOT an image<br/>";
// Do stuff ...
}
}
// ... Do more
} else {
echo "No results found. Please try a different search" . "<br>";
}
}
http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character
this might be help ful..
function strafter($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false)
return $string;
else
return(substr($string, $pos+strlen($substring)));
}
Something like this will work even for associative array.
foreach ($members as $user){
$Match = substr($user['column'][0], strpos($user['column'][0], "#") + 1);
$final_Array[$i]=$Match;
$i++;
}
print_r($final_Array)

Formatting String in PHP

I am trying to display numbers retrieved from the database, in a specific format in a text box.
There are two ways in which the numbers can be displayed.
When the total numbers are 10
in database (4608061019) Expected output 46-0806-1019
When the total numbers are 13
in database (4608061019100) Expected output 46-0806-1019-100
My progress so far:
While saving the value into the database I am using
preg_replace("/[^0-9]/","",$string); // to make sure all hardcoded "-" are removed while storing.
One possible (regex-using) approach:
$str = '4608061019';
$formatted = preg_replace(
'/(^\d{2}|\d{4})(?!$)/', '$1-', $str);
// 46-0806-1019
Demo. This function doesn't check the string's length - it just adds a hyphen after each relevant sequence of symbols (2 right after the beginning, 4 afterwards).
Easy! If you are sure that there are only these two options, then you can do this way:
Convert the number to an array of numbers:
$number = str_split($number);
Check the length:
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
Return the number:
return $number;
The full function here:
function tokenize($number)
{
$number = str_split($number);
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
return $number;
}
Output
echo tokenize(4608061019);
echo tokenize(4608061019100);
Output
46-0806-1019
46-0806-1019-100
Fiddle: http://codepad.viper-7.com/EVWeFR
Another alternative solution:
$parts = array(2,4,4,3);
$string = "4608061019100";
$i = 0;
$newString = '';
foreach ($parts as $part) {
$newString.=substr($string, $i, $part) ."-";
$i = $i+$part;
}
$newString = rtrim($newString, "-");
Output is:
string '46-0806-1019-100' (length=16)
Works for 46-0806-1019 too.
try it:
//$number = '4608061019';
$number = '4608061019100';
function formatImportantNumber($theNumber){
$formatedNumber = '';
if(strlen($theNumber)==10){
//46-0806-1019
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4);
}elseif(strlen($theNumber)==13){
//46-0806-1019-100
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4).'-'.substr($theNumber, 10, 3);
}else{
die('Invalid number formated')
}
return $formatedNumber;
}
echo formatImportantNumber($number);

How to truncate text from MySQL database with PHP? (Add '...' after characters limited)

I want to show snippets of 2 posts on the homepage. Here is the code I have:
function getPostsHome() {
$query = mysql_query("SELECT * FROM posts LIMIT 0,2") or die(mysql_error());
while($post = mysql_fetch_assoc($query)) {
echo "<h3>" . $post['Title'] . "</h3>";
echo "<p>" . $post['Content'] . "</p><br /><br />";
}
}
How do I truncate the Title to 25 characters, then '...', and the content to 100 characters, then '...'?
Thank you.
try with this
function getPostsHome() {
$query = mysql_query("SELECT * FROM posts LIMIT 0,2") or die(mysql_error());
while($post = mysql_fetch_assoc($query)) {
echo "<h3>" . (strlen($post['Title']) > 25 ? substr($post['Title'], 0, 25)."..." : $post['Title']) . "</h3>";
echo "<p>" . (strlen($post['Content']) > 100 ? substr($post['Content'], 0, 100)."..." : $post['Content']) . "</p><br /><br />";
}
}
sorry, now it's fixed
use substr() and strlen() functions:
Replace:
echo "<h3>" . $post['Title'] . "</h3>";
With:
if(strlen($post['Title']) >25)
echo "<h3>" . substr($post['Title'],0,25)."....</h3>";
else
echo "<h3>" . $post['Title'] . "</h3>";
Hope this help :D
<?php
function trunc($str, $len) {
if (strlen($str) > $len) {
$str = substr($str, 0, $len) . "...";
}
return $str;
}
$title = trunc($title, 25);
$content = trunc($content, 100);
echo $title;
?>
The other answers can produce strange results. Consider a string of 26 characters. In the other answers, this string is truncated to 25 chars + 3 "...". 28 chars for a string 26. That is not what you want. The good answer therefore is:
<?php
function trunc($str, $len) {
if (strlen($str) > $len+3) {
$str = substr($str, 0, $len) . "...";
}
return $str;
}
$title = trunc($title, 25);
$content = trunc($content, 100);
echo $title;
?>

How can I limit the total number of SimpleXML results?

I'm looking to limit to the first 5 results returned here.
This works, but it does not limit the data set:
<?php
foreach($sxml->status as $status){
$name = $status->user->name;
$image =$status->user->profile_image_url;
$update =$status->text;
$url = "http://twitter.com/" .$status->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
I've tried this:
<?php
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
?>
and am really kind of unsure why it doesn't work. If I simply do:
<?php echo $sxml->status[0]->user->name ?>
then I get the proper result. But when attempting it within the for loop, I get NULL.
Perhaps some kind of while? A different setup altogether? Thanks so much for any help you can give on this.
Change this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->$status[$n]->user->name;
$image = $sxml->$status[$n]->user->profile_image_url;
$update = $sxml->$status[$n]->text;
$url = "http://twitter.com/" . $sxml->$status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
To this:
for($n = 0; $n <= 5; $n++){
$name = $sxml->status[$n]->user->name;
$image = $sxml->status[$n]->user->profile_image_url;
$update = $sxml->status[$n]->text;
$url = "http://twitter.com/" . $sxml->status[$n]->user->screen_name;
echo "<li><img src=\"" . $image . "\" alt=\"" . $name . " image\" />" . $name . " " . $update . "</li>";
}
You accidentally were writing this:
<?php echo $sxml->$status[0]->user->name ?>
Where it was trying to us $status[0] as a variable variable and of course, that doesn't exist and is thus undefined/null.
If you had something that works, why overcomplicate things by changing everything? Just limit the processing to the first N entries.
$i = 0;
foreach ($sxml->status as $status) {
if (++$i > 5) {
// stop after 5 loops
break;
}
// the rest is identical
}
Btw, $n = 0; $n <= 5; $n++ will limit to the first 6 entries, not 5.
$n = 0; $n < 5; $n++ will do what you asked for.
Don't you mean
$n = 0; $n < 4; $n++
I've also tried this, and it works great :-)
foreach ($xml->item as $item) {
if (++$i > 5) { break; }
$item->title . '';
} //foreach()
Note I'm not using $i = 0; it seems to know that by default ;-)
I hope this helps some one.

Categories