Developers Archive for the 'php function explanations' Category

How search strings or replace single or multiple matches using PHP functions?

How search strings or replace single or multiple matches using PHP functions? Monday, February 25th, 2008

The preg_match() function can be used to match a regular expression against a given string. The function returns true if the match is successful, and can return all the captured sub-patterns in an array if an optional third parameter is passed by reference. Here’s an example:

name = “John Doe”;
// Simple match

$regex = “/[a-zA-Z\s]/”;

if (preg_match($regex, $name))
{
// Valid name }
// Match with sub-patterns and capture
$regex = ‘/^(\w+)\s(\w+)/’;
$matches = array();

if (preg_match ($regex, $name, $matches))
{
var_dump ($matches);
}

If you run the example, you will notice that the $matches array is populated, on return with the following values:

array(3) {
[0]=>string(12) “John Doe”
[1]=>string(5) “John”
[2]=>string(6) “Doe”
}

The first element of the array contains the entire matched string, while the second element (index 1) contains the first captured sub-pattern, and the third element contains the second matched sub-pattern.

Performing multiple matches:

The preg_match_all() function allows you to perform multiple matches on a given string based on a single regular expression. For example:

$string = “a1bb b2cc c2dd”;
$regex = “#([abc])\d#”;
$matches = array();

if (preg_match_all ($regex, $string, $matches))
{
var_dump ($matches);
}

This script outputs the following:

array(2) {
[0]=>
array(3) {
[0]=>
string(2) “a1″
[1]=>
string(2) “b2″
[2]=>
string(2) “c2″
}
[1]=>
array(3) {
[0]=>
string(1) “a”
[1]=>
string(1) “b”
[2]=>
string(1) “c”
}
}

All the whole-pattern matches are stored in the first sub-array of the result, while the first captured subpattern of every match is stored in the corresponding slot of the second sub-array.

Using PCRE to Replace Strings:

Whilst str_replace() is quite flexible, it still only works on ‘whole’ strings, that is, where you know the exact text to search for. Using preg_replace(), however, you can replace text that matches a pattern we specify. It is even possible to reuse captured subpatterns directly in the substitution string by prefixing their index with a dollar sign. In the example below, we use this technique to replace the entire matched pattern with a string that is composed using the first captured subpattern ($1).

$body = “[b]Make Me Bold![/b]”;
$regex = “@\[b\](.*?)\[/b\]@i”;
$replacement = ‘$1‘;
$body = preg_replace($regex, $replacement, $body);

Just like with str_replace(), we can pass arrays of search and replacement arguments; however, unlike str_replace(), we can also pass in an array of subjects on which to perform the search-and-replace operation. This can speed things up considerably, since the regular expression (or expressions) are compiled once and reused multiple times.

$subjects[’body’] = “[b]Make Me Bold![/b]”;
$subjects[’subject’] = “[i]Make Me Italics![/i]”;
$regex[] = “@\[b\](.*?)\[/b\]@i”;
$regex[] = “@\[i\](.*?)\[/i\]@i”;
$replacements[] = “$1“;
$replacements[] = “$1“;
$results = preg_replace($regex, $replacements, $subjects);

When you execute the code shown above, you will end up with an array that looks like this:

array(2) {
[”body”]=>
string(20) “Make Me Bold!”
[”subject”]=>
string(23) “Make Me Italic!”
}

Notice how the resulting array maintains the array structure of our $subjects array that we passed in, which, however, is not passed by reference, nor is it modified.

This concludes the basic of working with these functions, which are essential to any programmer. So be careful to understand them as they’re really indispensable.

FTP File access using PHP

FTP File access using PHP Tuesday, February 5th, 2008

With PHP, there’s always more than one way to accomplish a particular task. Take file upload, for example. Sure, you can do it the traditional way, using HTTP file upload and transferring the file directly to a location on your Web server’s disk. Or you can do it the more exotic way, and use the FTP protocol to upload in a two-step process: from your local disk to a Web server, and then to an FTP server.

PHP supports both FTP and HTTP upload methods natively, leaving it to you to make the best decision based on the design requirements of your application. Transferring a file using PHP’s FTP functions is almost the same as doing it using a traditional FTP client–as you’ll see even the function names are similar to standard FTP commands.

The ftp_connect() and ftp_login() functions are used to initiate a connection to the named FTP host, and log in to it using the supplied credentials.

Assuming a successful login, the ftp_put() function is used to upload the file from the working directory to the remote directory specified by the user and rename it to its original form. Note the addition of the special FTP_BINARY argument to ftp_put(), to specify that the file be transferred in binary (not ASCII) mode. Depending on the result code returned by the ftp_put() function, an error or success message is displayed to the user.

The ftp_get() function is used download a server file and save it locally. This function will take four parameters first is the connection ID, next is the server filename , next is the local file name and location and lastly the file transfer mode whether it is binary or ascii.

The ftp_close() function is used to end the FTP session, and the unlink() function is used to clean up by deleting the local copy of the file that was created in step (2).

tempnam() function

tempnam() function Monday, March 12th, 2007

tempnam($dir,$prefix)
This function is used to create a file with unique name.

First argument is for the directory to create file.Second argument is prefix of the filename.

Example:

$fName = tempnam(’/tmp’, ‘myFolder’);

$data = “test”;

$fp = fopen($fName, ‘w’);
fwrite($fp, $data);
fclose(fp);

unlink($filename);


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.