[PHP]Find array of bytes in file & replace it - php

i would like to find array of bytes in opened file and replace it with another one.
Any idea how to do that ? :)
This is how i read something from the file, everything works.
$current_file = basename($_FILES['fileToUpload']['name']);
$someInfoFromFile = 0;
if(isset($_POST["submit"]))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $current_file))
{
$fh = fopen($current_file, 'rw');
fseek($fh, 1000);
$someInfoFromFile = fread($fh, 2);
fclose($fh);
echo "Bytes read from file: " . $someInfoFromFile;
}
}
example:
Find $Buffer1 = array(10, 30, 30, 10);
Replace it with $Buffer2 = array(20, 20, 20, 20);
Maybe return if found or not.

str_replace() is binary safe, just make strings from your bytes. You can do this manually using the chr() function:
$search = chr(10) . chr(30) . chr(30) . chr(10);
$replace = chr(20) . chr(20) . chr(20) . chr(20);
Or build it from your array:
$search = pack('C*', ...$buffer1);
$replace = pack('C*', ...$buffer2);
Or maybe:
$search = join('', array_map('chr', $buffer1));
$replace = join('', array_map('chr', $buffer2));
Then:
$oldContents = file_get_contents($file); // or however you get it
$newContents = str_replace($search, $replace, $oldContents, $count);
echo "$count instances were replaced\n";

Related

how to replace a string in a stream for very large files

How can I replace a string in a file that cannot be fully loaded into memory
I can read it a few byes at a time, but how can I be sure I didn't read into the middle of my phrase?
I think I should save the last strlen(phrase) length of bytes and try to replace last+current
This is my WIP
function stream_str_replace(string $search, string $replace, $handle, int $length, &$count = null)
{
// assure $handle is a resource
if (!is_resource($handle)) {
throw new UnexpectedValueException('handle must be a valid stream resource');
}
// assure $handle is a stream resource
if ($resourceType = get_resource_type($handle) !== 'stream') {
throw new UnexpectedValueException('handle must be a valid stream resource, but is a "' . $resourceType . '"');
}
$sLength = strlen($search);
$lastInSLength = '';
while (!feof($handle)) {
$str = fread($handle, $length - $sLength - 1);
$batchCount = 0;
$res = str_replace($search, $replace, $lastInSLength . $str, $batchCount);
if ($batchCount) {
$count += $batchCount;
fseek($handle, -($length - 1));
fwrite($handle, $res); // this does not seem to work as I intend it to
}
$lastInSLength = substr($str, -$sLength);
}
}
$fh = fopen('sample.txt', 'r+');
stream_str_replace('consectetur', 'foo', $fh, 50, $count);
fclose($fh);

Find a phrase in a string

My code below is working
<?php
//load synonyms of words
$json_file = fopen("dict.json", "r") or die("Unable to open file!");
$js = fread($json_file, filesize("dict.json"));
$json = json_decode($js, true);
$text = "Hello my friend, today i am feeling good.";
$ar_text = explode(" ", $text);
foreach ($ar_text as $val)
{
$rand = rand(1, 3);
$randx = rand(1, 3);
if ($rand == $randx)
{
if (array_key_exists($val, $json))
{
$null = "{" . $val . "|";
$inc = $json[$val]['sinonim'];
$i = 1;
foreach ($inc as $siap)
{
$null .= $siap . "|";
if ($i == 4) break;
$i++;
}
$null .= "}";
$text = str_replace(" $val ", " $null ", $text);
//echo $null."<br>";
}
else
{
//echo "not found ".$val."<br>";
}
}
//echo $val;
}
$text = str_replace("|}", "}", $text);
echo $text;
//echo $json['mengaras']['tag'];
?>
i use explode to get word by word and then replace with word synonyms, how to get a phrase like "really good" and find it on dict.json.
Example: Hello, i am really good right now.
Output: Hello, i am {so fine|super fine|superb} now.
Use str_replace() - Replace all occurrences of the search string with the replacement string
$text = "Hello, i am really good right now.";
$find = "really good";
$replace = "so fine|super fine|superb";
$newtext= str_replace($find, $replace, $text);
OUTPUT:
Hello, i am so fine|super fine|superb right now.
You can do it this way too:
$text = 'Hello, i am really good right now.';
$match = 'really good';
$match_len = strlen($match);
$replace = array("so fine","super fine", "superb");
$pos = strpos($text, $match);
if($pos !== false){
echo "Word Found!";
$replace = implode("|", $replace);
$embed = '{' . $replace . '}';
echo $text_before . ' ' . $embed . ' ' . $text_after;
} else{
echo "Word Not Found!";
}
Output
Hello, i am {so fine|super fine|superb} right now.

Loop each array element in PHP

I am looking for a way to read each line of a text document as an array element.
<?php
$file = fopen("nums.txt", "r");
$i = 0;
$line = "";
$access_key = '1234567890';
while (!feof($file)) {
$line .= fgets($file);
}
$numbers = explode("\n", $line);
for ($i=0; $i < count($numbers); $i++) {
$ch = curl_init('http://apilayer.net/api/validate?access_key='.$access_key.'&number='.$numbers[$i].'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
$validationResult = json_decode($json, true);
echo $numbers[$i] . '</span>' . $validationResult['valid'] . ' ' . $validationResult['country_code'] . ' ' . $validationResult['carrier'];
}
fclose($file);
?>
Any tips are appreciated.
Cheers!
$numbers = explode(PHP_EOL, $line);
Is this what you wanted?
Updated with PHP_EOL
You could save a lot of work. Read into an array and trim the \n and/or \r and foreach():
$numbers = array_map('trim', file('nums.txt'));
foreach($numbers as $number) {
// echo $number
}
// Get the file content by path.
$file = file_get_contents($file);
// Break the file into array of lines.
$lines = preg_split('/\r*\n+|\r+/', $file);
// Remove last element as the last \r\n adds an extra element into the array.
array_pop($lines);
// Iterate over each line.
foreach($lines as $line_number => $line_content){
// do something...
}

How to remove [img] bbcode with php

I have a string
$content = "your image is [img]url to image.png[/img] now you can use it";
With php script I want
$content = "your image is now you can use it";
$content = "your image is [img]url to image.png[/img] now you can use it";
echo preg_replace("/\[img\](.+?)\[\/img\]/i", '', $content);
Output:
your image is now you can use it
If there is a single-instance of [img][/img], you can use a combination of substr() and strpos():
$first = substr($content, 0, strpos($content, '[img]'));
$end = substr($content, strpos($content, '[/img]') + 6);
$content = $first . $end;
If there can be multiple instances within the same string, you'll need to put it in a loop:
$openImg = strpos($content, '[img]');
while ($openImg !== false) {
$first = substr($content, 0, $openImg);
$end = substr($content, strpos($content, '[/img]') + 6);
$content = $first . $end;
$openImg = strpos($content, '[img]');
}

PHP modify TXT file

I have a ID.txt file that looks like this:
"http://something.net/something-ak/41389_718783565_1214898307_q.jpg"
"http://something.net/something-ak/372142_106502518141813_1189943482_q.jpg"
and so on
I want to use PHP to open the file and remove everything before the first " _ " and everything after the second " _ " so I wind up with this:
718783565
106502518141813
and so on
Thing is I don't really know how to do that.
This is what I have so far:
<?PHP
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);
// Remove everything before the first "_" and everything after the last "_".
// echo the line
}
fclose($file_handle);
?>
Can someone help me fille in the blanks?
This is what I would do, although a regex might be shorter or more efficient:
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode("\n", $line_of_text);
foreach ($parts as $str)
{
$str_parts = explode('_', $str); // Split string by _ into an array
array_shift($str_parts); // Remove first element
echo current($str_parts)."\n"; // echo current element and newline
// Same as $str_parts[0]
}
}
fclose($file_handle);
Demo: http://codepad.org/uFbVDtbR
Not a big deal, but $lines might be a better variable name there instead of $parts.
If you do need to write this back to the file, you can do this:
ob_start();
// code used above
$new_content = ob_get_clean();
file_put_contents("ID.txt", $new_content);
Relevant references:
http://php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.array-shift.php
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.file-put-contents.php
Just use file in a loop
$content = "";
foreach(file("ID.txt", FILE_SKIP_EMPTY_LINES) as $line){
$parts = explode('_', $line);
$content .= $parts[1] . "\n";
}
file_put_contents("ID.txt", $content);
If you want to achieve this by awk,
awk -F _ '{print $2}' ID.txt
Try this
preg_match('/(.*?)(.+?)(.*)/',$line,$matches);
$matches[2] will give the required string
This should work
<?php
// open files
$file_handle = fopen("ID.txt", "rb");
$new_file_handle = fopen("ID2.txt", "wb");
while (!feof($file_handle) ) {
$str = fgets($file_handle);
$start = strpos($str, '_'); // find first "_"
$end = strpos($str, '_', $start + 1); // find next "_"
$newstr = substr($str, $start + 1, $end - $start - 1) . "\n";
fputs($new_file_handle, $newstr);
}
// close files
fclose($file_handle);
fclose($new_file_handle);
// rename
rename("ID2.txt", "ID.txt");
$TXT = file_get_contents(__DIR__.'/in.txt');
$NewTXT = preg_replace('~^.+/[0-9]+_([0-9]+)_.+?$~mi', '$1', $TXT);
file_put_contents(__DIR__.'/out.txt', $NewTXT);
Just rename the .txt files accordingly.

Categories