PHP script adding a space in between every character - php

I have a little problem with a script I wrote.
It basically combines permutations of text in every possible order.
For some reason it is adding a space in between every character - can anyone figure out why?
Thanks in advance.
<?php
if(isset($_POST['submit']))
{
//pull in the perms
$perms = "{#A#B#C|#A#B#D|#A#B#E|#A#B#F|#A#C#D|#A#C#E|#A#C#F|#A#D#E|#A#D#F|#A#E#F|#B#C#D|#B#C#E|#B#C#F|#B#D#E|#B#D#F|#B#E#F|#C#D#E|#C#D#F|#C#E#F|#D#E#F}";
//open the box's
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
//this is the output
$tulis = fopen("output.txt","w+");
//read the box's
$box1 = fread($box1, filesize("box1.txt"));
$box2 = fread($box2, filesize("box2.txt"));
$box3 = fread($box3, filesize("box3.txt"));
$box4 = fread($box4, filesize("box4.txt"));
$box5 = fread($box5, filesize("box5.txt"));
$box6 = fread($box6, filesize("box6.txt"));
$perms = str_replace("#A","$box1",$perms);
$perms = str_replace("#B","$box2",$perms);
$perms = str_replace("#C","$box3",$perms);
$perms = str_replace("#D","$box4",$perms);
$perms = str_replace("#E","$box5",$perms);
$perms = str_replace("#F","$box6",$perms);
echo $text;
fwrite($tulis,$perms);
//close them properly
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
fclose($box1);
fclose($box2);
fclose($box3);
fclose($box4);
fclose($box5);
fclose($box6);
fclose($tulis);
}
//this means that if the submit button hasn't been pressed, print the form!
else
{
print '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="submit" name="submit"></input>
</form>
';
}
?>

Unless I am mistaking and I missed what you are trying to do, this script is doing pretty much like what you wrote, except that there are no str_replace and it creates permuations automatically for the number of files you provide (at least 3 for it to work properly) :
$files = array(
"box1.txt",
"box2.txt",
"box3.txt",
"box4.txt",
"box5.txt",
"box6.txt"
);
$contents = array();
foreach ($files as $index => $filename) {
$contents[$index] = trim(file_get_contents($filename), " \n\r");
}
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
file_put_contents('output.txt', $text);
Note that this version does not use fopen and trim the text read from the files to remove any whitespaces (CR and CL characters too) from the content.
** Edit **
This is the actual test program that I have made :
header('Content-type: text/plain; charset=utf-8');
$contents = array(
'A', 'B', 'C', 'D', 'E', 'F'
);
// fixed embedded loops method
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";
// Recursive method
function permutationRecursive( & $perms, $maxDepth, $contents = array(), $values = array(), $startIndex = 0) {
for ($i=$startIndex, $count=count($contents)-($maxDepth-1); $i<$count; $i++) {
array_push($values, $contents[$i]);
if ($maxDepth > 1) {
permutationRecursive( $perms, $maxDepth - 1, $contents, $values, $i + 1);
} else {
$perms[] = implode($values);
}
array_pop($values);
}
}
$perms = array();
permutationRecursive($perms, 3, $contents);
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";;
The output of this script is
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}

Related

How can I remove random amount of dots and get the last number?

I'm trying to strip all the dots and then get the number, and NAME[X] as an output.
My output is:
NAME..................................................................................................3
NAME2...................................................................................................24
NAME3...............................................................................................................................................5
NAME4.......................347
NAME5............................................................................................7
NAME6......................................................................9
I've tried something like this so far:
function introExcerpt($id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = 'my string';
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
// if (isset($lines[$i]) && substr(trim($lines[$i]), -1) !== '.') {
$intro.= $lines[$i].'<br />';
//}
}
$intro .= '</div></ul>';
return $intro;
}
Not sure exactly what your output should look like, but you may try just running preg_replace directly on the variable containing all lines:
$lines = preg_replace("/(NAME\d+)\.+(\d+)/", "$1[$2]", $lines);
This would generate the following output based on your sample input:
NAME[3]
NAME2[24]
NAME3[5]
NAME4[347]
NAME5[7]
NAME6[9]
You can use the following function:
function introExcerpt($str, $id = null, $introExcerptCut = null)
{
$fileInfo['intro'] = $str;
$introExcerpt = trim($fileInfo['intro']);
$lines = preg_split('/\r\n|\r|\n/', $introExcerpt);
$intro = '<div class="toc"><ul class="toc">';
for ($i = 0; $i < count($lines); $i++) {
$intro .= '<li>';
$tmpLineArray = explode('.', $lines[$i]);
array_filter($tmpLineArray, function ($value) {
return !is_null($value) && $value != '';
});
foreach ($tmpLineArray as $value) {
$intro .= $value . ' ';
}
$intro .= '</li>';
}
$intro .= '</ul></div>';
return $intro;
}
It is splitting the entire row into array using dot as separator and filters out the empty elements.

str_replace when matched and followed by space or special characters

I have a working function that strips profanity words.
The word list is compose of 1700 bad words.
My problem is that it censored
'badwords '
but not
'badwords.' , 'badwords' and the like.
If I chose to remove space after
$badword[$key] = $word;
instead of
$badword[$key] = $word." ";
then I would have a bigger problem because if the bad word is CON then it will stripped a word CONSTANT
My question is, how can i strip a WORD followed by special characters except space?
badword. badword# badword,
.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$badword = array();
$replacementword = array();
foreach ($words as $key => $word)
{
$badword[$key] = $word." ";
$replacementword[$key] = addStars($word);
}
return str_ireplace($badword,$replacementword,$data);
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Assuming that $data is a text that needs to be censored, badWordFilter() will return the text with bad words as *.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",",",""];
$dataList = explode(" ", $data);
$output = "";
foreach ($dataList as $check)
{
$temp = $check;
$doesContain = contains($check, $words);
if($doesContain != false){
foreach($specialCharacters as $character){
if($check == $doesContain . $character || $check == $character . $doesContain ){
$temp = addStars($doesContain);
}
}
}
$output .= $temp . " ";
}
return $output;
}
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return $a;
}
return false;
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Sandbox
I was able to answer my own question with the help of #maxchehab answer, but I can't declared his answer because it has fault at some area. I am posting this answer so others can use this code when they need a BAD WORD FILTER.
function badWordFinder($data)
{
$data = " " . $data . " "; //adding white space at the beginning and end of $data will help stripped bad words located at the begging and/or end.
$badwordlist = "bad,words,here,comma separated,no space before and after the word(s),multiple word is allowed"; //file_get_contents("badwordsnew.txt"); //
$badwords = explode(",", $badwordlist);
$capturedBadwords = array();
foreach ($badwords as $bad)
{
if(stripos($data, $bad))
{
array_push($capturedBadwords, $bad);
}
}
return badWordFilter($data, $capturedBadwords);
}
function badWordFilter($data, array $capturedBadwords)
{
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",","," "];
foreach ($specialCharacters as $endingAt)
{
foreach ($capturedBadwords as $bad)
{
$data = str_ireplace($bad.$endingAt, addStars($bad), $data);
}
}
return trim($data);
}
function addStars($bad)
{
$length = strlen($bad);
return "*" . substr($bad, 1, 1) . str_repeat("*", $length - 2)." ";
}
$str = 'i am bad words but i cant post it here because it is not allowed by the website some bad words# here with bad. ending in specia character but my code is badly strong so i can captured and striped those bad words.';
echo "$str<br><br>";
echo badWordFinder($str);

Saving hex data in binary using PHP does not work properly

I am learning PHP and files and I am trying to write some code that put data in a binary file.
here's my code:
Write
<?php
echo "\n\nWRITE: \n\n";
$c = array();
$data = '';
$c['name'] = 'abcdefghijklmnopqrstuvwxyz';
$data .= implode('', $c);
$fp = fopen('test.bin', 'wb');
$len = strlen($data);
echo "\nFILE CONTENT: $data (strlen: $len)\n\n";
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data{$i}));
fwrite($fp, pack("C", $hx));
}
echo "Last char is: $hx which mean: ";
echo chr(hexdec('7a'));
echo "\n--------------------------------------------\n";
fclose($fp);
Output
FILE CONTENT: abcdefghijklmnopqrstuvwxyz (strlen: 26)
Last char is: 7a which mean: z
Read
<?php
echo "\n--------------------------------------------\n";
echo "\n\nREAD: \n\n";
$fp = fopen('test.bin', 'rb');
$fseek = fseek($fp, 0, SEEK_SET);
if($fseek == -1) {
return FALSE;
}
$data = fread($fp, 26);
$arr = unpack("C*", $data);
$return = '';
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
$n = '';
$arr = array();
$arr['name'] = substr($return, 0, 26);
print_r($arr);
echo "\n--------------------------------------------\n";
Output
Array
(
[name] => abcdefghipqrstuvwxy
)
Where are the missing letters like the z, m, n or o ?
EDIT 6-3-14 7h36 am: I would like to have the .bin file not plain text if possible
You are trying to set HEX chars in a char (C - unsigned char) instruction.
echo "\t";
foreach( array('0x41', 65, 'a') as $o )
echo $o."\t";
echo "\n";
foreach( array('c*','C*','a*','A*','h*','H*','v*','n*','S*') as $o ){
echo $o . "\t";
foreach( array(0x41, 65, "a") as $oo ) {
echo pack($o, $oo);
echo "\t";
}
echo "\n";
}
If you run this, you will see quickly how pack works with the 3 different values of a (HEX, DEC and normal).
You have to use the h instruction to accomplish what you need.
function writeToFile($data) {
$fp = fopen(FILENAME, 'wb');
$len = strlen($data);
for ($i = 0; $i < $len; ++$i) {
$hx = dechex(ord($data[$i]));
$result = fwrite($fp, pack("h*", $hx));
if(!$result) {
// show something
}
}
fclose($fp);
}
Now, for read that data. You will need to use the same one h and split the string you get back (split it using str_split with the parameter 2 since it's HEX 00 = 0 and FF = 255 - assuming you won't go over 255). Since h returns an array with a single element. Once you get your string back, you need to convert the number you get from the ord in the writeToFile using the chr function.
function readFromFile($lenght, $pos = 0) {
$return = '';
$fp = fopen(FILENAME, 'rb');
if(!$fp) {
// show something
}
$fseek = fseek($fp, $pos, SEEK_SET);
if($fseek == -1) {
// show something
}
$data = fread($fp, $lenght);
$data = unpack("h*", $data);
$arr = str_split(current($data), 2);
foreach($arr as $val) {
$return .= chr(hexdec($val));
}
return $return;
}
Now, you create your string and write to the file:
$data = 'This should work properly, thanks for StackOverFlow!';
$len = strlen($data);
writeToFile($data);
Then read back:
echo readFromFile($len);
The content of your file will look like this:
E<86><96>7^B7<86>öWÆF^Bwö'¶^B^G'ö^GV'Æ<97>Â^BG<86>^Væ¶7^Bfö'^B5G^V6¶ôgV'dÆöw^R

Strict standard error in PHP

I've looked at similar posts here but couldn't crack a solution. I'm getting the Strict Standards: Only variables should be passed by reference error here on the strtolower($file['name']))), line. Tried hours now looking for a solution but couldn't figure out how to correct. Can you highlight where I've gone wrong?
Note: Code Edited as per #Kolink's suggestion below:
<?php
require_once 'upload_config.php';
$mydirectory = myUploadDir();
$uploaded_file_counter = 0;
$UploadLimit = $_POST['counter'];
for ($i = 0; $i <= $UploadLimit; $i++) {
$file_tag = 'filename' . $i;
$filename = $_FILES[$file_tag]['name'];
if ($filename != null) {
$rand = time();
$str = "$rand$filename";
// set folder name in here.
$filedir = myUploadDir();
//change the string format.
$string = $filedir . $str;
$patterns[0] = "/ /";
$patterns[1] = "/ /";
$patterns[1] = "/ /";
$replacements[1] = "_";
$dirname = strtolower(preg_replace($patterns, $replacements, $string));
//end of changing string format
//checking the permitted file types
if ($check_file_extentions) {
$allowedExtensions = allowedfiles();
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
/*if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) */
if (!in_array(array_reverse(explode(".", strtolower($file['name'])))[0], $allowedExtensions)) {
$fileUploadPermission = 0;
} else {
$fileUploadPermission = 1;
}
}
}
} else {
$fileUploadPermission = 1;
}
//end of checking the permitted file types
if ($fileUploadPermission) {
if (move_uploaded_file($_FILES[$file_tag]['tmp_name'], $dirname)) {
echo "<p>"; ?>
<div><?php echo "<img style='height:100px;width:200px' src='$dirname'>"; ?></div> <?php
echo "</p>";
$uploaded_file_counter += 1;
}
}
}
}
if ($uploaded_file_counter == 0) {
echo "<br /> <b style='font-weight:bold;color:red'>Opss! Please select an image file<b>";
} else {
echo "<br /> <b>You request " . $i . " image files to upload and " . $uploaded_file_counter . " files uploaded sucessfully</b>";
}
?>
end takes its argument by reference, since it modifies the original array by moving its internal pointer.
Since you appear to be using PHP 5.4, you can do this instead to get the last one:
if( !in_array(array_reverse(explode(".",strtolower($file['name'])))[0],$allowedExtensions))
That said, it's probably better to do it in several steps for readability:
$parts = explode(".",strtolower($file['name']));
$extension = $parts[count($parts)-1];
if( !in_array($extension,$allowedExtensions)) {

Getting last tweet with PHP

To get my last tweet in PHP I use this code :
function getTweets($tweetsToDisplay, $user_id) {
$twitterrequest = 'http://api.twitter.com/1/statuses/user_timeline.json?user_id=' . $user_id . '&include_rts=true&count=' . $tweetsToDisplay;
$twitterci = curl_init($twitterrequest);
curl_setopt($twitterci, CURLOPT_RETURNTRANSFER, TRUE);
$twitterinput = curl_exec($twitterci);
curl_close($twitterci);
return ($twitterinput);
}
$user_id = '99999999';
$var = json_decode(getTweets(1, $user_id));
$txt = $var[0]->text;
$txt = preg_replace('%(https?://)[^\s]*%', '$1...', $txt);
echo $txt;
Works fine but I want to get the date as well. How to extract it ?
I hope code below help you.
function getTimeline($count, $username) {
$url = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&count=.'$count;
$tweets = json_decode(file_get_contents($url),TRUE);
return $tweets;
}
You can try this simple PHP function that I created to catch latest tweets easily (does not require API authentication). Must be optimized :)
function getTweets($user, $count) {
$datas = file_get_contents('https://twitter.com/'.$user);
preg_match_all('/<p class="js-tweet-text tweet-text">(.*?)<\/p>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<s>(.?)<\/s>/', '$1', $matchetweets[1]);
$matchetweets[1] = preg_replace('/(class|dir|rel|data-expanded-url|data-pre-embedded|data-query-source)="(.*?)"/', '', $matchetweets[1]);
$matchetweets[1] = preg_replace('!\s+!', ' ', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
Usage
echo getTweets('nasa', 3);
UPDATE (10/15/2014) :
This version is out of date and not working anymore. Here is an updated PHP code to parse tweets easily.
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/', $datas, $matchetweets);
$matchetweets[1] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[1]);
for ($i = 1; $i <= $count; $i++) {
echo '<li>'.$matchetweets[1][$i].'</li>'."\n";
}
};
UPDATE (5/30/2015) :
function getTweets($user, $count) {
$datas = file_get_contents('https://mobile.twitter.com/'.$user);
preg_match_all('/<div class="tweet-text" data-id="\d*">(.*?)<\/div>/s', $datas, $matchetweets, PREG_SET_ORDER);
for ($i = 1; $i <= $count; $i++) {
$matchetweets[$i][0] = preg_replace('/<div class="dir-ltr" dir="ltr">/', '', $matchetweets[$i][0]);
$matchetweets[$i][0] = preg_replace('/\s+/', ' ', $matchetweets[$i][0]);
$matchetweets[$i][0] = str_replace('"> ', '">', $matchetweets[$i][0]);
echo '<li>'.$matchetweets[$i][0].'</li>'."\n";
}
};
Usage doesn't change. Minimum 1 tweet, maximum 20 tweets.
<?php
$date = $var[0]->created_at;
That should work!
Add this to bottom of your code.
$time = $var[0]->created_at;
echo $time;
Based on the Twitter API results from http://dev.twitter.com/doc/get/statuses/user_timeline, it appears that you could use the created_at param.
You have:
$txt = $var[0]->text;
If that works then add
$created = $vars[0]->created_at;
echo $txt;
echo "<span>".$created."</span>" ;

Categories