Archive for February 2011

Datos Enteros en Php

Un integer es un número del conjunto Z = {..., -2, -1, 0, 1, 2, ...}.

Sintaxis

Los enteros pueden ser especificados en notación decimal (base-10), hexadecimal (base-16) u octal (base-8), opcionalmente precedidos por un signo (- o +).
Si usa la notación octal, debe preceder el número con un 0 (cero), para usar la notación hexadecimal, preceda el número con 0x.

Ejemplo: Literales tipo entero

<?php
$a = 1234; // número decimal
$a = -123; // un número negativo
$a = 0123; // número octal (equivalente al 83 decimal)
$a = 0x1A; // número hexadecimal (equivalente al 26 decimal)
?>

Formalmente, la posible estructura para literales enteros es:

decimal     : [1-9][0-9]*
| 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal : 0[0-7]+

integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal


El tamaño de un entero es dependiente de la plataforma, aunque un valor máximo de aproximadamente dos billones es el valor usual (lo que es un valor de 32 bits con signo). PHP no soporta enteros sin signo. El tamaño de un entero puede determinarse a partir de PHP_INT_SIZE, o el valor máximo de PHP_INT_MAX a partir de PHP 4.4.0 y PHP 5.0.5.

aviso : Si un dígito inválido es pasado a un entero octal (p.ej. 8 o 9), el resto del número es ignorado.

Ejemplo: Curiosidad de valores octales

<?php
var_dump(01090); // 010 octal = 8 decimal
?>

Desbordamiento de enteros

Si especifica un número más allá de los límites del tipo integer, será interpretado en su lugar como un float. Asimismo, si realiza una operación que resulta en un número más allá de los límites del tipo integer, un float es retornado en su lugar.

<?php
$numero_grande = 2147483647;
var_dump($numero_grande);
// salida: int(2147483647)

$numero_grande = 2147483648;
var_dump($numero_grande);
// salida: float(2147483648)

// también es cierto para enteros hexadecimales especificados entre 2^31 y 2^32-1:
var_dump( 0xffffffff );
// salida: float(4294967295)

// esto no ocurre con los enteros indicados como hexadecimales más allá de 2^32-1:
var_dump( 0x100000000 );
// salida: int(2147483647)

$millon = 1000000;
$numero_grande = 50000 * $millon;
var_dump($numero_grande);
// salida: float(50000000000)
?>

No hay un operador de división de enteros en PHP. 1/2 produce el float 0.5. Puede moldear el valor a un entero para asegurarse de redondearlo hacia abajo, o puede usar la función round().

<?php
var_dump(25/7); // float(3.5714285714286)
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7)); // float(4)
?>

Conversión a entero

Para convertir explícitamente un valor a integer, use alguno de los moldeamientos (int) o (integer). Sin embargo, en la mayoría de casos no necesita usar el moldeamiento, ya que un valor será convertido automáticamente si un operador, función o estructura de control requiere un argumento tipo integer. También puede convertir un valor a entero con la función intval().

Desde booleans

FALSE producirá 0 (cero), y TRUE producirá 1 (uno).

Desde números de punto flotante

Cuando se realizan conversiones desde un flotante a un entero, el número será redondeado hacia cero.
Si el flotante se encuentra más allá de los límites del entero (usualmente +/- 2.15e+9 = 2^31), el resultado es indefinido, ya que el flotante no tiene suficiente precisión para dar un resultado entero exacto. No se producirá una advertencia, ¡ni siquiera una noticia en este caso!
aviso : Nunca moldee una fracción desconocida a integer, ya que esto en ocasiones produce resultados inesperados.

<?php
echo (int) ( (0.1+0.7) * 10 ); // imprime 7!
?>

Desde otros tipos

El comportamiento de convertir desde entero no es definido para otros tipos. Actualmente, el comportamiento es el mismo que si el valor fuera antes convertido a booleano. Sin embargo, no confíe en este comportamiente, ya que puede ser modificado sin aviso.

Resize images on the fly in PHP

To achieve this recipe, follow these simple steps:
1. Get the script and save it on your computer (I assume you named it timthumb.php)
2. Use a FTP program to connect to your server and create a new directory called scripts. Upload the timthumb.php file in it.
3. Once done, you can display images like this:
<img src="/scripts/timthumb.php?src=/images/whatever.jpg&h=150&w=150&zc=1" alt="" />

In other words, you just have to call the timthumb.php file and pass your image as a parameter. same goes for desired width or height.

Variables in PHP

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Note: $this is a special variable that can't be assigned.

<?php

$var = 'Bob';

$Var = 'Joe';

echo "$var, $Var"; // outputs "Bob, Joe"

$4site = 'not yet'; // invalid; starts with a number

$_4site = 'not yet'; // valid; starts with an underscore

$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.

?>

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?php

$foo = 'Bob'; // Assign the value 'Bob' to $foo

$bar = &$foo; // Reference $foo via $bar.

$bar = "My name is $bar"; // Alter $bar...

echo $bar;

echo $foo; // $foo is altered too.

?>

One important thing to note is that only named variables may be assigned by reference.

<?php

$foo = 25;

$bar = &$foo; // This is a valid assignment.

$bar = &(24 * 7); // Invalid; references an unnamed expression.

function test()

{

return 25;

}

$bar = &test(); // Invalid.

?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array.

Example: Default values of uninitialized variables

<?php

echo ($unset_bool ? "true" : "false"); // false

$unset_int += 25; // 0 + 25 => 25

echo $unset_string . "abc"; // "" . "abc" => "abc"

$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

PHP Code :- How to avoid Word breaking while we are using substr()

Here is a function I wrote to cut a string after x chars but it won't cut words... so you always get complete words, even if x is in the middle of a word:
function word_substr($str_String, $int_Length)
{
$str_String = trim($str_String);

$str_String = substr($str_String, 0, $int_Length);

$str_Revstr = strrev($str_String);
$str_LastChar = substr($str_Revstr, 0, 1);

if($str_LastChar == " ") // wurde der String in einem Wort geteilt?
{
//das Leerzeichen am Ende entfernen:
$str_String = substr($str_String, 0, -1);

return $str_String;
}
else
{

$arr_Words = explode(" ", $str_String);
$int_Elements = count($arr_Words);

if($int_Elements == 1)
{
return $arr_Words[0];
}
else
{
array_pop($arr_Words);
$str_String = implode(" ", $arr_Words);

return $str_String;
}
}
}


Here i am writing another function to avoid word breaking at the starting of a string. for example if you are doing db search for a keyword named "love". while displaying client wanted to display 100 character before and 100 character after that word. while we are displaying 100 character before there is a chance for breaking the word at the starting of a sentance, to avoid this we can use the following code:

//Function for checking start position of this sentence is a space or not
function SpaceChecking($content,$startpos)
{
$startpos=$startpos -1;
$data=substr("$content",($startpos),1);
if($data != " ")
{
//Call the same function Recursivly
$startpos=$this->SpaceChecking($content,($startpos-1));
}
return $startpos;
}

Store and saving binary data (images, coding, etc.) into MySql Database with PHP

An interesting topic in Mysql is to use the database to store binary data, such as images or html code. The first step is to create the database:

CREATE TABLE binary_data (
id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
descripction CHAR(50),
bin_data LONGBLOB,
filename CHAR(50),
filesize CHAR(50),
filetype CHAR(50)
);


The following script can be used to insert binary objects in the database from a browser. Note that the tag is used input type = "file" a form html to upload a file.


<HTML>
<HEAD><TITLE>Store and saving binary data (images, coding,
etc.) into MySql Database with PHP
</TITLE></HEAD>
<BODY>
<?php
if ($submit) {
//
Code that runs if I press the submit button
MYSQL_CONNECT( "localhost", "root", "password");
mysql_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"),
filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data(description,
bin_data,filename,filesize,filetype) ". "VALUES
('$form_description','$data',
'$form_data_name',
'$form_data_size','$form_data_type')");
$id= mysql_insert_id();
print "<p>Database ID: <b>$id</b>";
MYSQL_CLOSE();
} else {
// else
bring up the form for new data:
?>
<form method="post" action=" <?php echo $PHP_SELF; ?>"
enctype="multipart/form-data">
File Description:<br>
<input type="text" name="form_description" size="40">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>
Upload file to the database:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>
<?php
}
?>
</BODY>
</HTML>

Note the use of $ PHP_SELF predefined variable that contains the name of the script. This form is called himself regardless of the name that comes to the file.

The following script (getdata.php) can be used to recover data from the database, noting that the script expects to receive the variable $ id with id register to recover from the table.

<?php
if($id) {
@MYSQL_CONNECT( "localhost", "root", "contraseña");
@mysql_select_db( "binary_data");
$query = "select bin_data,filetype from binary_data where id=$id";
$result = @MYSQL_QUERY($query);
$data = @MYSQL_RESULT($result,0, "bin_data");
$type = @MYSQL_RESULT($result,0, "filetype");
Header( "Content-type: $type");
echo $data;
};
?>

To use an image that is obtained from the database can be used:


<img src="getdata.php?id=3">

Note as he passes the variable id to script to know what is the record to retrieve the base.



Boolean data type

PHP is allowing to write Boolean data type with uppercase or lowercase. But, writing with lowercase is more faster than uppercase. When found a constant, PHP do lookup hash constant name.

if ($var = TRUE) {
...
}

//this is more faster
if ($var = true) {
...
}

When using a Boolean value, 1 and 0 are more faster than true and false.

For creating zip file in php for the contents in a directory

This is a sample script for creating a zip file which includes all directories and files in a specified directory.

$files = $this->directoryToArray("$path/assets",TRUE);

$zip = new ZipArchive();
if($zip->open($zip_path,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) === true) {

            foreach($files as $filenames){
                if(!is_dir($filenames)){
                    $filename = substr($filenames,strrpos($filenames,"assets"));
                    $zip->addFile("$filenames","package/$filename");
                }
            }         

           
        }
         $zip->close();   

       
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=package.zip");
        readfile($zip_path);
--------------------------------------------------------------------------
function directoryToArray($directory, $recursive) {
        $array_items = array();
        if ($handle = opendir($directory)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($directory. "/" . $file)) {
                        if($recursive) {
                            $array_items = array_merge($array_items, $this->directoryToArray($directory. "/" . $file, $recursive));
                        }
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    } else {
                        $file = $directory . "/" . $file;
                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                    }
                }
            }
            closedir($handle);
        }
        return $array_items;
    }

Finding root parent of a child category in php

Using the below recursive function we can able to find the root parent category of a child category.

function getRootParent($id){
             $query = "select nav_parent_id from navigation_categories where nav_id='$id'";
            $result = $this->db->query($query);
                foreach($result->rows as $ids){
                    if($ids['nav_parent_id']==0){
                        return $id;
                    }else{
                        return $this->getRootParent($ids['nav_parent_id']);
                    }
                }
           
            return $id;
        }

Best & Popular PHP Frameworks

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. But often coding in PHP, or any language for that matter, can get rather monotonous and repetitive. That’s where a PHP framework can help.

The idea behind a framework is to offer a design you can use across multiple applications. All applications have a number of basic things in common. A framework is designed to provide a structure for those common elements (database interaction, presentation layer, application logic) so you spend less time writing up database interface code or presentation-layer interfaces and more time writing the application itself. The architecture represented by breaking an application up in this fashion is referred to as Model-View-Controller (MVC). Model refers to your data, View to your presentation layer, and Controller refers to the application or business logic.

In this article i have compiled a list of 14 best and popular PHP Frameworks which i think is best for developers, so give them a try and let me know if you like them.

1.Adroit Framework:

Adroit is a lightweight PHP 5 MVC framework that is geared towards helping you develop faster. The main motivation behind Adroit is to keep it simple, but provide useful features that developers want. Whether you’re just beginning web-application development, or a seasoned veteran, Adroit can help make that experience better.

2.Akelos Framework:

The Akelos PHP Framework is a web application development platform based on the MVC (Model View Controller) design pattern. Based on good practices, it allows you to:

  • Write views using Ajax easily
  • Control requests and responses through a controller
  • Manage internationalized applications
  • Communicate models and the database using simple conventions.

3.CakePHP:

CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

4.CodeIgniter:

CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks then this is for you.

5.LightVC Framework:

LightVC is a lightweight model-view-controller (MVC) framework without the model. This decoupling allows any model or object relation mapping (ORM) tool to be used, including none at all if one is not needed. LightVC is comparable to, although unlike, CakePHP, Code Igniter, symfony, Solar, and Zend Framework to name a few. It’s major difference is that it does not try to be a full “Web framework” and instead tries to solve the need for an MVC that isn’t coupled to other tools.

6.Opendelight Framework:

Opendelight is an Open Source PHP Application Development Framework. It encompasses the multi-tier architecture of web, and enables entreprise-grade web application development really fast and easy.

7.Prado Framework:

PRADO is a component-based and event-driven programming framework for developing Web applications in PHP 5. PRADO stands for  P HP  R apid A pplication  D evelopment  O bject-oriented. The sole requirement to run PRADO-based applications is a Web server supporting PHP 5.1.0 or higher.PRADO is free. You can use it to develop either open source or commercial applications.

8.Simple PHP Framework:

The Simple PHP Framework is a pragmatic approach to building websites with PHP 5. It’s geared towards web design shops and freelance programmers looking for a common foundation to quickly bring web projects to life. Without getting too technical, SPF follows the no-framework Framework method coined by Rasmus Lerdorf – with a little Active Record thrown in for good measure.

9.Symfony:

Symfony is a full-stack framework, a library of cohesive classes written in PHP. It provides an architecture, components and tools for developers to build complex web applications faster. Choosing symfony allows you to release your applications earlier, host and scale them without problem, and maintain them over time with no surprise. Symfony is based on experience. It does not reinvent the wheel: it uses most of the best practices of web development and integrates some great third-party libraries.

10.Recess Framework:

Recess is a restful PHP framework that provides a fun and enjoyable development experience for beginner and seasoned developers alike. If you want a full featured restful web application without having to master the command line or learn complicated deployment recipes, Recess is for you. Recess is fast, light-weight, and has a very small footprint—ideal for LAMP development and drag-and-drop deployment to shared hosts. Recess is a modern framework that uses a loosely-coupled Model-View-Controller architecture designed and optimized specifically for PHP 5.

11.Yii Framework:

Yii is a free, open-source Web application development framework written in PHP5 that promotes clean, DRY design and encourages rapid development. It works to streamline your application development and helps to ensure an extremely efficient, extensible, and maintainable end product. Being extremely performance optimized, Yii is a perfect choice for any sized project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe (presentation-to-persistence) to conform to your enterprise development guidelines. It comes packaged with tools to help test and debug your application, and has clear and comprehensive documentation.

12.Zend Framework:

Extending the art & spirit of PHP, Zend Framework is based on simplicity, object-oriented best practices, corporate friendly licensing, and a rigorously tested agile codebase. Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like  GoogleAmazonYahoo!Flickr , as well as API providers and cataloguers like  StrikeIron and ProgrammableWeb.

13.zephyr Framework:

zephyr is an ajax based framework for php5 developers. you can easily develop business applications using this robust framework. this is extremely easy to learn and very simple to implement. you can deliver a full fledged ajax application with strong business layer in backend within some minutes. installation and deployment of packages that you develop for zephyr is hassle free. moreover you will get all the features of most popular templating engine “smarty” and powerfull data access layer “adoDB”.

14.Zoop Framework:

Zoop has been in development since 2001 and in use for the last 6 years in a number of different production environments. While it predates the recent proliferation of PHP frameworks, it’s based on solid MVC principles, including separation of display, logic, and data layers. It’s designed to be efficient, modular, and extensible, striking a balance between lightweight and fully-featured.

 

ListFind / ListFindNoCase

The ListFind and ListFindNoCase are identical functions other than the obvious reason; one is case sensative and the other is not. If you use list to store data or move data, the ListFind function is incredibly useful. Also, the ListFind function works well when rerading comma seperated lists or scraping data from other websites.

The Function:


<?php

function ListFind($list,$value,$delimiter=",")
{
$delimiter = substr($delimiter,1);
$a = explode($delimiter,$list);
for($i=0;$i<count($a);$i++)
{
if( strstr($a[$i],$value))
{
return true ;
}
}
return false;
}

function ListFindNoCase($list,$value,$delimiter=",")
{
$a = explode($delimiter,$list);
for ($i=0;$i<count($a);$i++)
{
if(stristr($a[$i],$value))
{
return true;
}
}
return false;
}


?>

Usage:

<?php
$list = "Car,Truck,Boat,Plane,Train" ;
$find = "car";
if(ListFind($list,$find))
{
echo $find . " found!";
}
?>


Using the ListFind to find 'car' will fail since the ListFind is case sensetive. However, the ListFindNoCase will do the trick!

<?php
$list = "Car,Truck,Boat,Plane,Train" ;
$find = "car";
if( ListFindNoCase($list,$find))
{
echo $find . " found!";
}
?>

The result in this case will be : car found!

instant5dollars


Hello

Get instant and unlimited $5 payments directly to your PayPal account!

Join Instant5Dollars.com and for every referral you get, it will directly pay you $5 in your PayPal account.

Instant5Dollars also has a Downline Builder that lets you get more referrals in each program, and residual income for life.

Wait. There's more! You can download a bonus package with which you can generate more income.

We will give you an action plan so you know how to make money with Instant5Dollars.com

Join now!

http://instant5dollars.com/index.php?referid=obama4u


To your success
Alfred Spiteri

MYSQL String functions makes life easier

MYSQL strings function can make your life easier for you.You can use combination of string function to get the complex result needed in some project.String function in mysql helps us to extract what we want from a string and that can avoid lot of code.The common String functions available in MYSQL can be found on the link http://dev.mysql.com/doc/refman/5.1/en/string-functions.html

Use of MYSQL String function.

consider the following table which contains caseId and you have to extract maximum number at the last of caseId, those belong to id 1.

caseId id Value
JET/2005-2006/1 1 15
JET/2005-2006/2 1 25
JET/2005-2006/1 2 15
JET/2005-2006/2 1 2
JET/2005-2006/2 2 12
JET/2005-2006/3 1 5

you can use the following query to get the result.

SELECT max(substring(caseId,locate(”/”,caseId,locate(”/”,caseId)+1)+1)) as maxCaseId FROM `test` WHERE id=1

The result of the query is as follows.

maxCaseId
3

This query work as follows.

inner locate function get’s first occurrence of “/” [let's 4].and outer locate function get first occurrence of “/” [let's 17] in the string starting from position 4+1=5.so finally in subString function will give all the string values after position 17+1=18.So by this we will have all numbers those belongs to id 1.now finally max function will get max number within all the numbers found by substring function.

if you want to get the maximum integral value, you got to cast it to an integer - otherwise, on having a caseId value like JET/2005-2006/23, it would still return 3 as maximum & not 23.

SELECT
MAX(0 + SUBSTRING(caseId, LOCATE(’/', caseId, LOCATE(’/', caseId) + 1) + 1)) AS maxCaseId
FROM `test` WHERE id = 1;

SELECT
MAX(0 + RIGHT(caseId, LOCATE(”/”, REVERSE(caseId)) - 1)) AS maxCaseId
FROM `test` WHERE id = 1;

even reversing strings can avoid looping of locate.

SELECT MAX(RIGHT(caseId, LOCATE(”/”, REVERSE(caseId)) - 1)) AS maxCaseId FROM `test` WHERE id = 1

So This is just an example to explain uses of string functions available in MySql. There may be lot’s of other situation where you can use string function provided by mysql and get your work done rather than getting result by writing complex logic in programming.

acessing xml in php sent by other script

There are several situation where we need to accept xml as input in php file which is sent by other scripts like flash/php/perl etc.

To accept xml as input in php, first you need to check that content-type which is being passed by source script has to be in "text/xml" format.

Now in your PHP script you can accept xml input by the following code.

$xml_str=file_get_contents("php://input");
//where $xml_str will have xml string passed by the source script.


Mengambil Pola Teks

Sering sekali kita berhubungan dengan input atau data yang berhubungan dengan teks dan berkepentingan untuk mengambil sebagian dari teks tersebut berdasarkan suatu pola. Bagaimana kita melakukan hal tersebut ? Salah satu cara paling efisien adalah dengan menggunakan fungsi preg_match() seperti yang akan saya jelaskan di bawah ini.

Fungsi preg_match()

Fungsi preg_match() adalah fungsi yang digunakkan untuk mencari suatu pola di dalam subjek teks ktia dengan menggunakan regular expression.

Sintaks dasarnya adalah sebagai berikut:

int preg_match ( string pattern, string subject [, array &matches [, int flags [, int offset]]] )

tapi untuk penyederhanaan maka sintaks berikut adalah yang akan kita gunakan :

int preg_match ( string pattern, string subject [, array &matches] )

Dimana :
  • pattern adalah definisi pola dalam regex yang ingin kita cocokkan dengan subjek kita
  • subject adalah subjek teks yang akan kita cocokkan
  • matches adalah array tempat menyimpan hasil pencocokan teks dengan pola regex yang telah kita definisikan. Ini adalah parameter optional (boleh ada atau tidak).
Contoh Kasus

Misalkan kita memiliki suatu urutan teks sebagai berikut :

Nama=PHP;Website=http://www.komputasiawan.com;Komentar=Belajar Regex itu sangat berguna, terutama untuk pengolahan teks;Topik=Pengolahan Teks;

Dari untaian teks tersebut saya ingin mengambil url website yang terdapat di dalamnya, yaitu http://www.komputasiawan.com. Bagaimana caranya ?

Pertama kita tentukan pola regex yang pas untuk mengambil nilai dari entri Website, yaitu :

Website=(.+?);

Setelah itu kita masukkan sebagai parameter pertama fungsi preg_match() dengan diapit beberapa karakter khusus sebagai pengapit pola regex (/,@, &, dsbnya).

Contoh code-nya adalah sebagai berikut :


<?php
$teks = "Nama=PHP;Website=http://www.komputasiawan.com;Komentar=Belajar Regex itu sangat berguna, terutama untuk pengolahan teks;Topik=Pengolahan Teks;";

$pola = "&Website=(.+?);&";

$hasil_arr = array();
$hasil_akhir = "";

preg_match($pola, $teks, $hasil_arr);
$hasil_akhir = $hasil_arr[1];

echo "<pre>";
print_r($hasil_arr);

echo "URL website = $hasil_akhir";
echo "</pre>";
?>


Dan berikut adalah hasil yang didapatkan :


Array
(
[0] => Website=http://www.komputasiawan.com;
[1] => http://www.komputasiawan.com
)
URL website = http://www.komputasiawan.com


Sederhana bukan ?

Penutup

Penggunaan pola regular expression (regex) di PHP dengan menggunakan fungsi preg_match() sangat berguna untuk mengolah teks sederhana sampai dengan yang kompleks. Hal yang perlu kita kuasai adalah pengetahuan mengenai regex itu sendiri.

Demikian artikel ini dibuat, semoga dapat berguna. Nantikan artikel selanjutnya.

open files in a directory with dir() in php

<?php
//Open send directory
if(@$dir = @dir("send"))
{
//List files in send directory
while (($file = $dir->read()) !== false)
{
echo "filename: " . $file . "<br />";
}
$dir->close();
}
else
{
echo 'directory not opened';
}
?>

output :
 1)
directory not opened

2)
filename: .
filename: ..
filename: sendsms.html
filename: sendsms.php
filename: send_vard.php
filename: send_vcard_sms.html
filename: smser.php

note :
"send" is a directory name