Archive for the ‘php’ Category

php how to replace many space with one space

October 25, 2009


$str = preg_replace('/\s+/', ' ', $str); //" \n\n\n" will end up as " \n"
$str = preg_replace('/\x20+/', ' ', $str); //only space

how to detect ajax request

October 20, 2009

ajax request will send additional header

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
echo 'ajax';

stackoverflow

The page you are looking for is temporarily unavailable. Please try again later.

October 14, 2009

server configuration php5-cgi, php5-tidy nginx, debian etch.
Tidy configuration tab-size=>0 can trigger this error. Just change the tab-size value to be greater than 0 to fix

tab-size => 1

php add leading zero

October 3, 2009


echo $num; // 1
$str = sprintf('%02d', $num, 2);
echo $str; //01

php get the number of days between two dates

October 2, 2009


$timestamp = strtotime($end_date) - strtotime($start_date);
$days = round($timestamp / 86400);

this code only works on linux box.

make all image clickable

June 6, 2009

make all image in a page to have a direct link.


$content = ''; //content of a page with <img tag
$content = preg_replace('/<img alt=".*" \/>/',
'<a href="\\1">\</a>', $content);

preg_replace manual

Fatal Error: Class ‘tidy’ not found

April 22, 2009

solution

#pecl install tidy
#apt-get install php5-tidy

you might have to add extension=tidy.so into php.ini

php tidy extension loaded but not working

php include vs include_once vs require vs require_once

March 8, 2009

All work the same way. But require_once is the fastest in linux.

PHP require vs. include vs. require_once vs. include_once Performance Test

extract text from ms office

February 24, 2009

Interesting program to extract text

  • catdoc – extract text from ms word
  • xls2cvs – extract text from ms excell
  • pdftotext – extract text from pdf
  • ppthtml – extract text from ms. power point

Then a simple php function can capture the output eg:

function extractWord($word_file)
{
if (file_exists($word_file)
{
// prevent malicious command execution
exec("/usr/bin/catdoc -w ' . escapeshellarg($word_file), $output);

// $output is an array corresponding to lines of output
return join("\n", $output);
}
}

extracting text from office and pdf file

import/export csv

February 12, 2009

a very handy php function fgetcsv and fputcsv


header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv; filename=document_" . date("Ymd") .".csv");

http://www.modwest.com/help/kb6-135.html
http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm