Format Sentences, format number and remove extra spaces. All in one solution

We had a requirement, where we were asked to format the content from a big database table. And the format includes making sentences to sentence case, format simple numbers to comma separated numbers within those sentences and remove the extra spaces. Here is the solution. Hope this helps you.
function formatString($string){
 //number formatting
 $string1 = preg_replace_callback('/\d+/', function($match){return number_format($match[0]);}, $string);
 
 //removing extra spaces
 $string2 = preg_replace('/\s+/', ' ', $string1);
 
 //sentence case
 $sentences = preg_split('/([.?!]+)/', $string2, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

$str = "it was an awesome               day. i bought shares for 23000      and sold at 27000 in just 2        hours. i had a profit of 4000 INR. isn't it great?";
echo formatString($str);

Huge data Excel download using PHP

Ah! It was always a problem to download huge data in excel format. Tried the best library available 'PHPExcel' but the issue persists with memory limit and time taken to generate and download.

But here is the promising solution found after spending ages searching on Google. You can find it here. The author himself says "Never run out of memory with PHPExcel again".

You need to download it and include xlsxwriter.class.php where you want to fetch the data from DB and through it on to browser or save to a particular location.

Let's get started.
Below is the logic to generate the file and store in the current directory. If you want to store is at the desired location, specify the location for the method writeToFile.

include_once("xlsxwriter.class.php");
$writer = new XLSXWriter();
$data = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('output.xlsx');
In case if you want to download it on the fly use the below logic.
include_once("xlsxwriter.class.php");
$writer = new XLSXWriter();
$data = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);
$filename = 'output.xlsx';

$writer = new XLSXWriter();
$writer->writeSheet($data);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');

$writer->writeToStdOut();
Through this library, you can even set the column type. Please visit the official URL for more information.

WYSIWYG super light editor with jQuery & Bootstrap

Yes! It is. Summernote is the super light WYSIWYG editor for the web. It supports most of the features tinyMCE or CKEditor does but with smallest Javascript & CSS files.

You can download Summernote from here. It is the official website for the same. It has very simple getting started tutorial. 

This is article will show you how to start with summernote and couple of fixes or plugin which you don't find on the official website.

Getting started:
If you want to download and start with, click here.
For CDN, place below snippet under head tag.


<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script> 

<!-- include summernote css/js -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>
  
Now create a textarea and attach summernote to it.

<textarea id="Description" name="Description"></textarea>

$(document).ready(function(){
   $('#Description).summernote();
});

When you don't want to show/use all the buttons in the toolbar, then you can choose/define like below
$('#Description').summernote({toolbar: [
       // [groupName, [list of button]]
       ['style', ['bold', 'italic', 'underline', 'clear']],
       ['font', ['strikethrough', 'superscript', 'subscript']],
       ['fontsize', ['fontsize']],
       ['para', ['ul', 'ol', 'paragraph']],
       ['insert', ['picture', 'link', 'video', 'table', 'hr']]
     ]});

That's it! But, if you are using summernote in Bootstrap modal, then there is a small problem. Whenever you click on Image, Video or link buttons another modal opens up with the options and while closing the second modal it will close all the modals. Quick fix: You can add this line of code as option to summernote.
$('#Description').summernote({
  dialogsInBody: true,
  toolbar: [ 
    // toolbar code if needed
  ]
});

Summernote inserts base64 code (image data URL) for any image inserted. If you don't want to store image data URL in the text (as it will hold huge data), then you can use below code:
$('#Description').summernote({
  dialogsInBody: true,
  toolbar: [ 
    // toolbar code if needed
  ],
  callbacks: {
      onImageUpload: function(image) {
          uploadImage(image[0]);
      }
  }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("file", image);
    $.ajax({
        url: SITE_URL + "admin/upload-image",
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('').attr('src', url);
            $('#Descrpition').summernote("insertNode", image[0]);
        },
        error: function(data) {
            //console.log(data);
        }
    });
}

PHP code to upload an image to any directory and return URL for the image:

if (isset($_FILES['file']['name'])) {
    if (! $_FILES['file']['error']) {
        $name = md5(rand(100, 200));
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $filename = $name . '.' . $ext;
        $destination = $this->getMediaPath() . 'images/' . $filename;
        $location = $_FILES["file"]["tmp_name"];
        move_uploaded_file($location, $destination);
        echo 'media/images/' . $filename;
    } else {
        echo "Ooops!  Your upload triggered the following error:  " . $_FILES['file']['error'];
    }
}            

That's it...

Generate documentation for PHP Code using phpDocumentor

What is phpDocumentor?
phpDocumentor is the simple and best tool to generate API documentation for PHP source code. 


Downloading & installing phpDocumentor:
There are several dependencies to install phpDocumentor you can find them on official website i.e., here

To install phpDocumentor using PEAR type below command
  • In windows, run command prompt as administrator. Goto xampp/php folder and type
    pear channel-discover pear.phpdoc.org
    pear install phpdoc/phpDocumentor
  • In linux, open terminal and type (if install xampp for linux then goto xampp/bin folder)
    pear channel-discover pear.phpdoc.org
    pear install phpdoc/phpDocumentor
Generate API using phpDocumentor:
  • In windows, goto  phpdoc.bat folder and run phpdoc  command for source directory to destination
     phpdoc -d <source directory of php code> -t <destination directory>
  • In Linux, goto [phpdocumentor installation folder]/bin/ and run command
     phpdoc -d <source directory of php> -t <destination directory>
Note:
If in case, installation method through PEAR gives you below error. Try downloading phar and proceed
Fatal error: Uncaught TypeError: Argument 1 passed to Monolog\ErrorHandler::handleException() must be an instance of Exception...

Download .phar from here
To generate API run the below command from php directory with the location of .phar file
php phpDocumentor.phar -d <source directory of php code> -t <destination directory>

If you find any error related to Graphviz, download and install software from here. Set the environment variable for Graphviz/bin directory for 'dot' executable file.