PHP how to add variable string after strpos - php

I am getting all the data of a webpage then searching it for a certain string. I use strpos to find the location, then once found i would like to create a variable that stores all the information 64 characters past the strpos.
E.g:
$begin = strpos($page, 'content123') //Then once position is found on webpage, add another 64 characters beyond the 3 (of 123)
To clarify, i am getting file contents from a web page, searching the page data for a position (e.g 'content), then once i have found the position, I would like the program to grab everything after this marker by 64 characters (this is a variable)
EDIT:
$begin = strpos($page, 'https://i2.au.reastatic.net/800x600/') + strlen('https://i2.au.reastatic.net/800x600/');
$end = strpos($page, '/image.jpg');
$ImageName = substr($page, $begin, ($end - $begin));
$ImageContent = 'https://i2.au.reastatic.net/800x600/' . $ImageName . '/image.jpg';
P.S, not sure why people are down voting a legitimate question? I thought this was a place to help each other.
Thanks

it seems that your code is correct
$page = 'https://i2.au.reastatic.net/800x600/ImageName/image.jpg';
$begin = strpos($page, 'https://i2.au.reastatic.net/800x600/') + strlen('https://i2.au.reastatic.net/800x600/');
$end = strpos($page, '/image.jpg');
$ImageName = substr($page, $begin, ($end - $begin));
$ImageContent = 'https://i2.au.reastatic.net/800x600/' . $ImageName . '/image.jpg';
echo $ImageContent;

Related

Trying to change all image file names in a folder to the date and time image was taken

I have a folder of images that I am trying to change to be the date and time the picture was taken. I managed to make it work for the most part, however if the image has the same DateTimeOriginal (to the second), the subsequent images are deleted and replaced with the last one. This is a problem when I use burst on my camera.
I am trying to have the code add "_1" after each file name, unless the file name exists, then I want the "_1" to increase by 1. So far, the code I have will catch the first duplicate name and work properly, but every other matching filename after just deletes the file before it that has the same name (which was just renamed by the code).
In case it makes a difference, I am using XAMPP to run the PHP code in a local directory on my windows 10 PC, but I do test it online as well and have the same outcome.
The following is the code I have come up with by piecing together other code that I have found, and then attempting to customize it. I have a general understanding of PHP through trial and error, but have no education. I feel like I should be using a "while" statement while(file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) instead of or in conjunction with the current if statement I have if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg'))
The entire code I am using is here:
<?php
$count=1;
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
date_default_timezone_set('America/Edmonton');
$dirloc = "pictures/$file";
$newdirloc = "NewPictures/$file";
$exif_data = exif_read_data ($dirloc, $file, 0, true);
$exifString = $exif_data['DateTimeOriginal'];
$exifPieces = explode(":", $exifString);
$newExifString = $exifPieces[0] . "-" . $exifPieces[1] . "-" . $exifPieces[2] . ":" . $exifPieces[3] . ":" . $exifPieces[4];
$exifTimestamp = strtotime($newExifString);
$timestamp = date("y-m-d_H-i-s", $exifTimestamp);
if (file_exists('pictures/'.$timestamp.'_'.$count.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$count.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($file.' has now been changed to '.$timestamp.'_'.$count.'.jpg (Increased count from existing file)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_'.$count.'.jpg');
}
else {
echo ($file.' has now been changed to '.$timestamp.'_1.jpg (Unique File)<br>');
rename('pictures/'.$file, 'pictures/'.$timestamp.'_1.jpg');
}
}
}
?>
Thanks for helping this newbie figure this out!
Edit:
I think I've narrowed it down to a simpler question.
If it is possible to see if $ANY_NUMBER is in fact any number, what would I say $ANY_NUMBER is = to? With this change, I should be able to get rid of the count=1 at the start, and if it is true that it is any number in that [6] spot, than I should be able to say that count= that [6] spot. Does that make sense?
if (file_exists('pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg')) {
$ExistingFile = 'pictures/'.$timestamp.'_'.$ANY_NUMBER.'.jpg';
$delimiters = ['-', '_', '.'];
$newStr = str_replace($delimiters, $delimiters[0], $ExistingFile);
$NamePieces = explode("-", $newStr);
$count = $NamePieces[6];
++$count;
echo ($count);
}

PHP variable between 2 string positions

I have tried searching the forums but still unsure how to do this.
I am extracting a web link from a webpage, and the start and end are always the same but there is a variable i want to get.
E.g http://www.example.com/images/$VARIABLE/image.jpg
$position1 = http://www.example.com/images/
$position2 = image.jpg
I need to get the variable. On the webpage the $position 2 is listed more than once (image.jpg)
I have tried all sorts of things and nothing works so far.
Thank you
$begin = strpos($page, $position1) + strlen($position1);
$end = strpos($page, $position2);
$ImageName = substr($page, $begin, ($end - $begin));
I think the problem is that if image.jpg occurs before http://www.example.com/images/, then just trying to use your code won't work.
A slight fix would be to start the search for $position2 where you found the first part by adding a start point in the strpos() function...
$begin = strpos($page, $position1) + strlen($position1);
$end = strpos($page, $position2, $begin);
$ImageName = substr($page, $begin, ($end - $begin) - 1);
with
$page = "some test image.jpg some more text
blurb that is in the middle http://www.example.com/images/VARIABLE/image.jpg
some even more text image.jpg";
the code finds
VARIABLE
A regex as suggested by #user3783243 may also work, but you may also need a constraint of how long the parameter is likely to be.

Convert a full string (represented in exponential format) back in number in PHP

I've been searching for converting my exponential number string into an exact number.
So, I've an exponential number stored as string in MySQL. I want to convert back this string in the exact number.
But It seems the number is quite big and crosses the boundary and provide me wrong data.
While I tried following code in various format but result is not in proper format.
policy_number = "2.9992020830803E+18";
number_format($policy_number, 0,'.','');
// Output
2999202083080300032
(float) $policy_number;
// Output
2.9992020830803E+18
sscanf($policy_number, "%f")[0];
// Output
2.9992020830803E+18
floatval($policy_number);
// Output
2.9992020830803E+18
gmp_init("2.9992020830803E+18");
gmp_strval($policy_number);
// Output
0
"2.9992020830803E+18" + 0;
// Output
2.9992020830803E+18
Please show me the right way to convert it.
Updated
I agree with Ed Cottrell that your problem is how you are storing your data in the db. However, if this is a project where you are already looking at a large set of data that is already stored as an exponent then this function I wrote should work for you. It should work for positive and negative bases and exponents. It basically mimics the way you would do the operation by hand.
I was not able to figure out a way to do it using math functions. If someone knows how to do it better please post. In the meantime, I had fun writing this.
Hope it helps you out!
function getRealNumber($number){
//Parse the base and exponent.
preg_match('/^(.*?)E[\-|\+](.*?)$/', $number, $data);
$base = $data[1];
$exp = $data[2];
//Test to see if the base is negative.
if(preg_match('/\-/', $base)){
$base = str_replace('-', '', $base);
$isNegative = TRUE;
}
//Capture the offset of the decimal point.
preg_match('/\./', $base, $position, PREG_OFFSET_CAPTURE);
$offset = $position[0][1]; //This is the offset of the decimal point.
$string = str_replace('.', '', $base); //Get numbers without decimal.
$length = strlen($string); //Get the length of string.
//Test to see if we are adding zeros to the end or beginning of string.
if(preg_match('/E\+/', $number)){
//Let's move the decimal.
if($length > ($exp + $offset)){
$string = substr_replace($string, '.', ($exp + $offset), 0);
} else {
$string = $string . str_repeat('0', $exp - ($length - $offset));
}
}elseif(preg_match('/E\-/', $number)){
//Calculate the number of zeros needed to add and append them.
if($offset > $exp){
$string = substr_replace($string, '.', $offset, 0);
} else {
$string = '0.' . str_repeat('0', $exp - $offset) . $string;
}
}
//Add the negative sign if we need to.
if(!$isNegative){
return $string;
} else {
return '-' . $string;
}
}
$policy_number = "2.9992020830803E+18";
echo getRealNumber($policy_number);
//Will output 2999202083080300000

how to partially mask/hide email address using PHP

Im trying to achieve the following with PHP
sample#gmail.com => s*****#gmail.com
sa#yahoo.com => **#yahoo.com
sampleaddress#hotmail.com => samplead*****#hotmail.com
I want to hide last five characters in the portion that stays before '#'
I can write long code to do this by splitting and then replacing based on lengths, but Im sure there must be an easy way to do this using PHP functions, any help please?
UPDATE:
Im adding my code here, Im sure its not efficient, and thats the reason Im asking it here
$email = 'sampleuser#gmail.com';
$star_string = '';
$expl_set = explode('#',$email);
if(strlen ($expl_set[0]) > 5){$no_stars = 5; }else{$no_stars = strlen ($expl_set[0]); }
for($i=0;$i<$no_stars; $i++)
{
$star_string.='*';
}
$masked_email = substr($expl_set[0], 0, -5).$star_string.'#'.$expl_set[1];
You can wrap it into a function, making it easier to call multiple times.
Basically, split the address and the domain, replace $mask number of characters in the end of the string (default 5) with *, or the length of the address if it's shorter than the amount of masked characters.
function mask_email($email, $masks = 5) {
$array = explode("#", $email);
$string_length = strlen($array[0]);
if ($string_length < $masks)
$masks = $string_length;
$result = substr($array[0], 0, -$masks) . str_repeat('*', $masks);
return $result."#".$array[1];
}
The above would be used like this
echo mask_email("test#test.com")."\n";
echo mask_email("longeremail#test.com");
which would ouput this
****#test.com
longer*****#test.com
You can also specify the number you want filtered by using the second parameter, which is optional.
echo mask_email("longeremail#test.com", 2); // Output: longerema**#test.com
Live demo

How to get correctly content and avoid breaking html tags using strip_tags with substr?

In my page I have some post previews from RSS feeds. Every post preview shows about 300 characters. When a user clicks on expanding button, then the #post-preview is replaced with the #post. The #post shows the rest of the post.
Everything fine with this but the format of the #post is not good, not readable. So I thought of allowing <br><b><p> tags, it will make it ok to be read. Because I don't want the user to be distracted, I want the tags to be allowed after the 300 chars.
With the following method, it is possible to break some tags where the $start ends and $rest starts. This means no good readable output.
$start = strip_tags(substr($entry->description, 0, 300));
$rest = strip_tags(substr($entry->description, 300), '<b><p><br>');
$start . $rest;
My question is how can I keep $start and $rest the same (no tags) until the 300 char, and after that $rest will show the formatted post? Are there any other ways of doing this?
Here is an example of a RSS feed structure (from view page source).
<item><guid isPermaLink="false"></guid><pubDate></pubDate><atom:updated></atom:updated><category domain=""></category><title></title><description></description><link></link><author></author></item>
I am looking for a way that does not kill performance.
Something like:
$start = substr($entry->description, 0, 300);
if(($pos = stripos($start, "<")) !== false) {
$start = strip_tags(substr($start, 0, $pos));
$rest = substr($entry->description, $pos);
}
else {
$start = strip_tags($start);
$rest = substr($entry->description, 300);
}
Ok, it's just a concept. Gets first 300 chars and checks for broken tag. If broken cut before it and get $rest from this point. If not broken just strip and get rest. There is at least 1 problem:
you never now the length of the $start(after strip_tags could be nothing left), could use loop with length checking but eeee... efficiency
EDIT
Ok, get it:
$start = "";
$chars = 400;
while(strlen($start) < 300) {
$start = strip_tags(substr($rss, 0, $chars));
$chars += 50;
}
$pos = stripos($rss, substr($start, strlen($start) - 50));
$rest = substr($rss, $pos+50);
Ok, little nasty and there are some cases on which it fails(with repetable text probably:D), tested on Ideone

Categories