Archive for November 2011

preg_match() or search a string / substring in php

<?php

$string='hello world';
if(preg_match("/hel/",$string))
  {
     echo 'word or characted found';
  }
else
  {  echo 'word or characted not found';
  }

?>
output :word or characted found


<?php

$string='hello world';
if(preg_match("/z/",$string))
  {
     echo 'word or characted found';
  }
else
  {  echo 'word or characted not found';
  }

?>

output :word or characted not found

<?php

$string='hello world';
$searchstring='hel';
if(preg_match("/$searchstring/",$string))
  {
     echo 'word or characted found';
  }
else
  {  echo 'word or characted not found';
  }

?>
output :word or characted found
<?php

$string='hello world';
$searchstring='z';
if(preg_match("/$searchstring/",$string))
  {
     echo 'word or characted found';
  }
else
  {  echo 'word or characted not found';
  }

?>

output :word or characted not found
<?php

$string='hello world';
$searchstring='hello';
if(preg_match("/$searchstring/",$string))
  {
     echo 'word or characted found';
  }
else
  {  echo 'word or characted not found';
  }

?>
output : word or characted found

Que se puede hacer con PHP?

PHP puede hacer cualquier cosa que se pueda hacer con un script CGI, como procesar la información de formularios, generar páginas con contenidos dinámicos, o enviar y recibir cookies. Y esto no es todo, se puede hacer mucho más.

Existen tres campos en los que se usan scripts escritos en PHP.

Scripts del lado del servidor. Este es el campo más tradicional y el principal foco de trabajo. Se necesitan tres cosas para que esto funcione. El intérprete PHP (CGI ó módulo), un servidor web y un navegador. Es necesario correr el servidor web con PHP instalado. El resultado del programa PHP se puede obtener a través del navegador, conectándose con el servidor web. Consultar la sección Instrucciones de instalación para más información.

Scripts en la línea de comandos. Puede crear un script PHP y correrlo sin ningún servidor web o navegador. Solamente necesita el intérprete PHP para usarlo de esta manera. Este tipo de uso es ideal para scripts ejecutados regularmente desde cron (en *nix o Linux) o el Planificador de tareas (en Windows). Estos scripts también pueden ser usados para tareas simples de procesamiento de texto.

Escribir aplicaciones de interfaz gráfica. Probablemente PHP no sea el lenguaje más apropiado para escribir aplicaciones gráficas, pero si conoce bien PHP, y quisiera utilizar algunas características avanzadas en programas clientes, puede utilizar PHP-GTK para escribir dichos programas. También es posible escribir aplicaciones independientes de una plataforma. PHP-GTK es una extensión de PHP, no disponible en la distribución principal.

PHP puede ser utilizado en cualquiera de los principales sistemas operativos del mercado, incluyendo Linux, muchas variantes Unix (incluyendo HP-UX, Solaris y OpenBSD), Microsoft Windows, Mac OS X, RISC OS y probablemente alguno más. PHP soporta la mayoría de servidores web de hoy en día, incluyendo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape e iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene módulos disponibles para la mayoría de los servidores, para aquellos otros que soporten el estándar CGI, PHP puede usarse como procesador CGI.

De modo que, con PHP tiene la libertad de elegir el sistema operativo y el servidor de su gusto. También tiene la posibilidad de usar programación procedimental o programación orientada a objetos. Aunque no todas las características estándar de la programación orientada a objetos están implementadas en la versión actual de PHP, muchas bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) están escritas íntegramente usando programación orientada a objetos.

Con PHP no se encuentra limitado a resultados en HTML. Entre las habilidades de PHP se incluyen: creación de imágenes, archivos PDF y películas Flash (usando libswf y Ming) sobre la marcha. Tambié puede presentar otros resultados, como XHTM y archivos XML. PHP puede autogenerar éstos archivos y almacenarlos en el sistema de archivos en vez de presentarlos en la pantalla.

Quizás la característica más potente y destacable de PHP es su soporte para una gran cantidad de bases de datos. Escribir un interfaz vía web para una base de datos es una tarea simple con PHP. Las siguientes bases de datos están soportadas actualmente:

  • Adabas D
  • Ingres
  • Oracle (OCI7 and OCI8)
  • dBase
  • InterBase
  • Ovrimos
  • Empress
  • FrontBase
  • PostgreSQL
  • FilePro (read-only)
  • mSQL
  • Solid
  • Hyperwave
  • Direct MS-SQL
  • Sybase
  • IBM DB2
  • MySQL
  • Velocis
  • Informix
  • ODBC
  • Unix dbm

También contamos con una extensión DBX de abstracción de base de datos que permite usar de forma transparente cualquier base de datos soportada por la extensión. Adicionalmente, PHP soporta ODBC (el Estándar Abierto de Conexión con Bases de Datos), asi que puede conectarse a cualquier base de datos que soporte tal estándar.

PHP también cuenta con soporte para comunicarse con otros servicios usando protocolos tales como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos otros. También se pueden crear sockets puros. PHP soporta WDDX para el intercambio de datos entre lenguajes de programación en web. Y hablando de interconexión, PHP puede utilizar objetos Java de forma transparente como objetos PHP Y la extensión de CORBA puede ser utilizada para acceder a objetos remotos.

PHP tiene unas características muy útiles para el procesamiento de texto, desde expresiones regulares POSIX extendidas o tipo Perl hasta procesadores de documentos XML. Para procesar y acceder a documentos XML, soportamos los estándares SAX y DOM. Puede utilizar la extensión XSLT para transformar documentos XML.

Si usa PHP en el campo del comercio electrónico, encontrará muy útiles las funciones Cybercash, CyberMUT, VeriSign Payflow Pro y CCVS para sus programas de pago.

Para terminar, contamos con muchas otras extensiones muy interesantes, las funciones del motor de búsquedas mnoGoSearch, funciones para pasarelas de IRC, utilidades de compresión (gzip, bz2),, conversión de calendarios, traducción, etc.

Use custom slug manipulation for sluggable field in Propel

In my situation, I need to use Turkish characters converted for url. You need to override cleanupSlugPart function:

protected static function cleanupSlugPart($slug, $replacement = '-')
{
// convert turkish chars
$str = str_replace('ı','i',$slug);
$str = str_replace('İ','I',$str);
$str = str_replace('ç','c',$str);
$str = str_replace('Ç','C',$str);
$str = str_replace('ğ','g',$str);
$str = str_replace('Ğ','G',$str);
$str = str_replace('ş','s',$str);
$str = str_replace('Ş','S',$str);
$str = str_replace('ü','u',$str);
$str = str_replace('Ü','U',$str);
$str = str_replace('ö','o',$str);
$slug = str_replace('Ö','O',$str);

// lowercase
if (function_exists('mb_strtolower')) {
$slug = mb_strtolower($slug);
} else {
$slug = strtolower($slug);
}

...

PHP comparison operators

PHP comparison operator means using PHP operators compare two things or two variable. Suppose that we have two variable $a=10 and $b=20. We have to know which variable is small or big. In that case we use comparison operators. Different types of PHP comparison operators are given below

( == ) Equal : It returns true if $a and $b is same. 
( != ) Not Equal : It returns true if $a and $b is not same. 
( === ) Identical : It returns true when $a and $b is same and same type. 
( !== ) Not Identical : It returns true when $a and $b is not same and same type.
( < ) Less than : Returns true if ($a<$b) $a is less than $b. 
( > ) Greater than : Returns true if ($a<$b) $a is greater than $b. 

PHP comparison operators first check the condition then return true or false. If true then execute the program otherwise not execute the program.

Now take a look at the example below

<?php
$a
=10;
$b
=20;
$c
=10;
echo
($a==$c);
echo
"<br>";
echo
($a===$c);
echo
"<br>";
echo
($a!=$b);
echo
"<br>";
echo
($a!==$b);
echo
"<br>";
echo
($a<$b);
echo
"<br>";
echo
($b>$c);
?>


Downloading as csv/excel file in php using headers

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/vnd.ms-excel" );
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".date("Y-m-d").".csv\";");
header("Content-Transfer-Encoding:� binary");
header("Content-Length: ".strlen($output));

Avoid using Large String Concatenation

When do concatenation string, avoid uniting with large size string. It can obstructing code execution that really can display more faster.

//large string concatenation
$title = ‘title’;
$body = ‘…a very large block…’;
echo “Subject: $title\n\n$body”;

//avoid large string concatenation
$title = ‘title’;
$body = ‘…a very large block…’;
echo “Subject: $title\n\n”;
echo $body;

Installing PNP


I am working on Ubuntu (Debian)

echo 'Installing PHP...';
sudo apt-get install --yes --force-yes php5-cli php5-dev php5-fpm php5-pgsql php5-mcrypt php5-gd php5-curl php-pear

echo 'Installing nginx...';
sudo apt-get --yes --force-yes install nginx


echo 'Installing Postgres...';
sudo add-apt-repository ppa:pitti/postgresql
echo 'Updating...';
sudo apt-get --yes --force-yes update
echo 'Upgrading...';
sudo apt-get --yes --force-yes dist-upgrade
echo 'Installing postgres...';
sudo apt-get --yes --force-yes install postgresql-plpython-9.1

Php For Statement

PHP For statement is used when you want to loop the code for number of times,
until condition is met.

Syntax :
for (initialization; condition; increment)
{
code ...
}

Example :

<?php

for ($val=1; $val<=3; $val++)

{

echo "This is the text.<br />";

}

?>

Output of this Php code is :

This is the text.
This is the text.
This is the text.


PHP Ming

Ming is a library for generating Macromedia Flash files (.swf), written in C, and includes useful utilities for working with .swf files.You can use this library with PHP,Perl, ruby etc using wrapper.Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them.

Installation PHP
go to command prompt and type the following command

sudo apt-get install php5-ming


Restart web server.That's it folks.




for more info how to use this with php visit

http://in.php.net/manual/en/intro.ming.php

MySQL DATE TIME Format Conversion


Date Time Conversion in PHP Mysql


To convert DATE TIME FIELD Values in Database to a particular format we can use  mysql function DATE_FORMAT()

eg: the default datatime format in mysql is 2012-07-18 10:20:32 .
To get the date in DD-MM-YY use 
DATE_FORMAT( '2012-07-18 10:20:32 ','%d - %m - %Y') 
prints 18-7-2012

MySQL DATE_FORMAT() Letter Representations
SpecifierDescription
%aAbbreviated weekday name (Sun..Sat)
%bAbbreviated month name (Jan..Dec)
%cMonth, numeric (0..12)
%DDay of the month with English suffix (0th1st2nd3rd, …)
%dDay of the month, numeric (00..31)
%eDay of the month, numeric (0..31)
%fMicroseconds (000000..999999)
%HHour (00..23)
%hHour (01..12)
%IHour (01..12)
%iMinutes, numeric (00..59)
%jDay of year (001..366)
%kHour (0..23)
%lHour (1..12)
%MMonth name (January..December)
%mMonth, numeric (00..12)
%pAM or PM
%rTime, 12-hour (hh:mm:ss followed by AM or PM)
%SSeconds (00..59)
%sSeconds (00..59)
%TTime, 24-hour (hh:mm:ss)
%UWeek (00..53), where Sunday is the first day of the week
%uWeek (00..53), where Monday is the first day of the week
%VWeek (01..53), where Sunday is the first day of the week; used with %X
%vWeek (01..53), where Monday is the first day of the week; used with %x
%WWeekday name (Sunday..Saturday)
%wDay of the week (0=Sunday..6=Saturday)
%XYear for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%xYear for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%YYear, numeric, four digits
%yYear, numeric (two digits)
%%A literal “%” character
%xx, for any “x” not listed above