Archive for the ‘Codes’ Category
PHP string manipulation 3
Written by Codes Tips on August 1, 2009 – 1:00 pm -This is the third part about how to manipulate strings in PHP.
Replace all occurrences of sub strings with a replacement string
If you wanna replace all occurrence of a substring inside a string you should use the function str_replace passing as first argument the string(or array of strings) you wanna search, second argument the string(or array of strings) you wanna make the replace, the third is the string you wanna search in and the fourth argument is the number of replacements the function should make. It returns a string after all replacements have been made.
Declaration: mixed str_replace ( mixed $SearchFor, mixed $ReplaceWith , mixed $String[, int &$number] )
Example:
<?php $string= "This is a str_replace Function Test"; $searchFor = array("Function","Test"); $replaceWith = array("function","test"); echo str_replace($searchFor,$replaceWith,$string); ?>
Output: This is a str_replace function test
Split string one by one
To tokenize string in php you can you the function strtok in order to split a string. Each smaller string it’s separated by a delimeter. It takes as a first argument the string that will be split and the second the delimeter that it is used to split it.
You should call the first time the function as strtok($String,$delimiter) and returns the first string that is delimited. Any subsequent calls of the function should be like strto($delimiter(s)), because the function keeps into memory the variable $String that it’s delimited.
You can specify multiple delimiter
Declaration: string strtok(string $String, string $delimiter(s))
Example:
<? $string = "This is an strtok Function Test"; $tok = strtok($string, " "); while ($tok !== false) { echo "String=$tok<br />"; $tok = strtok(" ");//returns the next splitted string in the $string variable } ?>
Output:
String=This
String=is
String=an
String=strtok
String=Function
String=Test
Split a string by a delimeter
Disadvantage of strtok function it’s that you should call it every time you wanna split the string. You can use explode function in order to split the string and returns an array of string with all the string splitted. The first argument is the delimiter, the second the string you wanna split and you can also specify an optional integer argument that specify the limit of strings splitted.
Declaration: array xplode(string $delimiter , string $String[, int $limit ])
Example:
<? $string = "This is an explode Function Test"; $explodedstring = explode(" ", $string,3); foreach($explodedstring as $substring) echo $substring.'<br />'; ?>
Output:
This
is
an explode Function Test
Union elements of array in a string
If you wanna join array elements into 1 string you should call the function implode. The first argument that you should pass to the function is the separation and the second one the array of string.
Declaration: string implode ( string $separator , array $Strings)
Example:
<? $strings = array('This','is','a', 'implode','function','test'); $separator = " "; echo implode($separator,$strings); ?>
Output:
This is a implode function test
Replace a string by regular expression
You can use regular expression in php to replace using the function preg_replace. You should pass the first argument as a regular expression pattern - it can be a string or an array of string, the second is the string or array of string that you use to replace the pattern, third argument is the string you search in. The final two arguments are optional, first parameter is the limit of replacement you should make and the final one is the value of replacements that have been made in the string.
Declaration: mixed preg_replace (mixed $regularExpression, mixed $replaceWith, mixed $String [, int $limit= -1 [, int &$count ]] )
Example:
<? $string = "This is a preg_replace bad, words, Function Test"; $pattern = "(\w+,)"; $replaceWith = ""; echo preg_replace($pattern, $replaceWith, $string)."<br />"; ?>
Output:
This is a preg_replace Function Test
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL | 1 Comment »
PHP string manipulation 2
Written by Codes Tips on July 31, 2009 – 2:34 pm -This is the second part of the how you can manipulate string in PHP.
Find length of a string
If you want to find out how many characters have a string you can use the function strlen. If you have to pass 1 argument as the string you wish you find out the length and it returns an integer.
Declaration: int strlen(string text)
Example:
Output: 31
Find a sub string inside a string
To find a first occurrence of a string inside other you should use the function strstr and pass it 2 arguments. First argument should be the string in which you wanna look and the second should be the string you search. It returns part of the first occurrence until the end of the string you search in.
Declaration: string strstr(string searchIn,string lookfor)
Example:
Output: strstr Function Test
Find a string inside other string(case insensitive)
To find an occurrence of a string inside another with case insensitive activated you should use the function stristr. It has the same parameters as the strstr, but it also finds case insensitive strings.
Declaration: string stristr(string SearchIn, string lookFor)
Example:
Output: StrStr Function Test
Find position of first occurrence of a string inside another
To find the position of the first occurrence of a string you can use the function strpos. You should pass two arguments. The first parameter is the string you wanna search in and the second is a the string you are looking for. You can specify an additional argument, an offset that indicates from where position the search should begin.
Declaration: int strpos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )
Example:
Output: 11
Find a position of a string inside another(case insensitive)
You can use the function strripos and it has the same arguments as strpos, but it searches for case insensitives.
Declaration: int strripos ( string $SearchIn, mixed $SearchFor[, int $offset= 0 ] )
How to return parts of a string
To return parts of a string you should use the substr function and pass it 2 arguments and 1 optional. The first argument is the string you wanna return a part of a string, second is the start position from where you wanna begin crop the string. You can also specify an argument with the length that the function should crop.
Declaration: string substr ( string $SearchIn , int $from [,int $length])
Example:
Output: is a substr
Insert after each end of line in string a html br tag
To insert html tag br after the new lines in a string you can use the function nl2br. Function takes one neccessary argument and one optional. First is a string where it will be inserted the br tag and the second one is a boolean that indicates if the replacement is a XHTML compatible line breaks(default value is TRUE).
Declaration: string nl2br(string $InsertIn [,bool $isXHTML= true])
Example:
Output:
This is a nl2br<br /> Function<br /> Test
PHP string manipulation - part 1 - PHP string manipulation - part 3
Tags: Codes, PHP
Posted in Codes, PHP/MYSQL | 2 Comments »
PHP string manipulation
Written by Codes Tips on July 28, 2009 – 2:53 pm -This is a first part of PHP string manipulation.
It’s extremelly useful to know how to manipulate strings in PHP. This tutorial will guide you through how to use the functions that PHP offers.
A string in PHP it’s defined in php in a variable assigning a single or double quote value like:
$string = ‘This is a test string’;
$string = “This is a test string”;
Make all letters from string lowercase
To make every letter of a string in lowercase you should use the function strtolower like this:
<? $string= "This is a strtolower Function Test"; echo strtolower($string); ?>
The ouput will be: this is a strtolower function test
Make all letters of a string uppercase
You should use the function strtoupper in order to make every letter of the string in uppercase:
<? $string= "This is a strtoupper Function Test"; echo strtoupper($string); ?>
The ouput of will be: THIS IS A STRTOUPPER FUNCTION TEST
Capitalize first letter of each word in a sentence with ucwords
To make a sentence more estetic we can capitalize first letter of each word in a sentence with the function ucwords().
<? $string= "This is a ucwords Function Test"; echo ucwords($string); ?> Output: This Is A Ucwords Function Test
This function touch only the first letter of each word and leave other characters like they are. We can improve the way how the string is displayed by combining with the strtolower function.
<? $string= "ThiS is a ucwords FunctioN Test"; echo ucwords(strtolower($string)); ?>
Output will be:This Is A Ucwords Function Test
Remove tabs,spaces,new lines from beginning and end of a string
To remove spaces,tabs and new lines from the beginning and end of a string you should use the function trim(). This function accepts as an input a string, that will be cleaned and returns a string without spaces,tabs and new lines.
<? $string= "\t \nThis is a trim Function Test "; echo trim($string); ?>
Output: This is a trim Function Test
Remove spaces,tabs and new lines from begining of a string
Similar like trim we can use ltrim to remove spaces,tabs and new lines from the beginning of a string
<?php $string= "\t \nThis is a trim Function Test \t\t "; echo ltrim($string); ?>
Output: This is a trim Function Test
Remove spaces,tabs and new lines from the end of a string
Similar like ltrim we can use rtrim to remove characters that we don’t need:
<? $string= "\t \nThis is a rtrim Function Test \t\t "; echo rtrim($string); ?>
Remove tags from a string
To remove tags from a string you should use strip_tags to have a clean string without tags
<?php $string= "<pre>This is a trim Function Test</ pre>"; echo strip_tags($string); ?>
Tags: PHP, PHP/MYSQL
Posted in Codes, PHP/MYSQL | 1 Comment »
Delphi http post
Written by Codes Tips on June 2, 2009 – 9:42 am -To post some data through http protocol in Delphi you can use TIDHttp component.
TIDHttp has a function Post that takes 2, first parameter is the url where you wanna post data and the second is the data you need to post.
The first parameter of Post function is a string and the second one is a TStringList.
Delphi sample code to post data through http. First put in the uses clause IdHTTP
function PostData:string; var param:TStringList; valid:boolean; url,text:string; http:TIDHttp; begin http := TIDHttp.Create(nil); http.HandleRedirects := true; http.ReadTimeout := 5000; param:=TStringList.create; param.Clear; param.Add('parameter1=1'); param.Add('parameter2=2'); param.Add('parameter3=3'); valid:=true; url:='http://www.examplesite.com/script.php'; try text:=http.Post(url,param); except on E:Exception do begin valid:=false; end; end; if valid then PostData:= text else PostData := ''; end;
You can call the function like this:
textPostData := PostData();
This function returns empty string if it was an error posting data, if not it returns the text that is returned from the url that we posted data.
We created a new TIDHttp variable at runtime and put the properties ReadTimeout to 5 seconds(timeout of the connection) and HandleRedirects to true, because the url where we post data can redirect us to other page from where we get the result.
Tags: borland delphi, Delphi
Posted in Codes, Delphi | No Comments »
PHP cpanel scripts
Written by Codes Tips on June 1, 2009 – 8:50 am -Intro
To automate an action in PHP for cpanel it’s very easy. You just need to know some information about your cpanel. You can find this information on your browser link bar.
$cpanel_user - the username that you use to log into your cpanel
$cpanel_password - the password for cpanel.
$cpanel_host - your cpanel host. You can find this after you login to cpanel, right before ‘http://’ until ‘:’.
$cpanel_skin - cpanel skin. You can find this after ‘/frontend/’, default is ‘x’.
HTML Form
You can use this html forms to make the scripts for cpanel, you can add your own fields that you need.
<form action="cpaneladd.php" method="POST"> <table> <tr><td colspan="2" align="center"> <b>Cpanel info</b></td></tr><tr><td align="right">Cpanel host: </td><td align="left"> <input type="text" name="cpanelhost"></td></tr> <tr><td align="right">Cpanel username:</td><td align="left"> <input type="text" name="cpaneluser"></td></tr> <tr><td align="right">Cpanel password:</td><td align="left"> <input type="text" name="cpanelpass"></td></tr> <tr><td align="right">Cpanel skin:</td><td align="left"> <input type="text" name="cpanelskin" values="x"></td></tr> </table> </form>
I made a list with some useful functions that you can use for cpanel:
1. Adding a database in cpanel
$newdb = "db_name"; $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user: $cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin /sql/adddb.html?db=$new_db"); $result=curl_exec ($curl); curl_close ($curl);
2. Adding a user to database in cpanel
$db_user = "dbuser"; $db = "database"; $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user: $cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin/ sql/addusertodb.html?user={$cpanel_user}_{$db_user} &db={$cpanel_user}_{$db}&ALL=ALL"); $result=curl_exec ($curl); curl_close ($curl);
3. Delete a user in cpanel
$userdb="userdb"; $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user: $cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin/ sql/deluser.html?user=".$cpanel_user."_".$userdb); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result=curl_exec ($curl); curl_close ($curl);
4. Delete a database in cpanel
$db="db"; $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, "http://$cpanel_user: $cpanel_password@$cpanel_host:2082/frontend/$cpanel_skin /sql/deldb.html?db=".$cpanel_user."_".$db); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result=curl_exec ($curl); curl_close ($curl);
Tags: Codes, PHP
Posted in Codes, PHP/MYSQL, Scripts | No Comments »
PHP xml to csv
Written by Codes Tips on May 23, 2009 – 7:48 am -To create a csv file from a xml in PHP 5.0 it’s very simple, we will just have to write some lines.
We will use the SimpleXML extension that come from PHP 5.0.
SimpleXML reads an entire xml into an object that we can iterate through his properties.
To write to the csv output file we will use fputcsv.
fputcsv formats a line as csv and writes it to the file.
Suppose we are having this xml named cars.xml:
<?xml version='1.0'?> <cars> <car> <color>blue</color> <price>2000</price> </car> <car> <color>red</color> <price>10000</price> </car> <car> <color>black</color> <price>5000</price> </car> </cars>
First we should read our xml using simplexml_load_file passing the name of the file and returns an object with all the properties and values of the csv:
$xml = simplexml_load_file($filexml);
After reading it we should iterate through all the child nodes of cars and write it to the output file using fputcsv specifying the object,delimiter and enclosure. We should first convert the object into an array in order to write it to the csv:
foreach ($xml->car as $car) fputcsv($f, get_object_vars($car),',','"');
Here is the complete source code that converts xml to csv in php 5.0:
<? $filexml='cars.xml'; if (file_exists($filexml)) { $xml = simplexml_load_file($filexml); $f = fopen('cars.csv', 'w'); foreach ($xml->car as $car) { fputcsv($f, get_object_vars($car),',','"'); } fclose($f); } ?>
Download php source code for converting xml into a csv
Tags: Codes, PHP
Posted in Codes, PHP/MYSQL, Scripts | No Comments »
PHP multithreading using cURL
Written by Codes Tips on May 23, 2009 – 3:00 am -If you wanna get some information from servers using the protocols like http or ftp in PHP you can use cURL to do multithreading.
Multithreading is a term used when we do more jobs in parallel.
First I assume you know what cURL is and what you can it. If you are new to cURL, you can check one of my article on posting data with cURL , it will give you a brief intro to cURL.
To create this with cURL you should know what the following PHP functions do:
curl_multi_init - initialize a new cURL multi handle. It will return the cURL handle on success and FALSE on error.
curl_multi_add_handle — Add a cURL handle to a cURL multi handle.
curl_multi_exec — Runs all the curl handle in the cURL multi handle in parallel.
curl_multi_remove_handle — Removes a cURL handle from a cURL multi handle.
curl_multi_close — close the cURL multi handle.
You will need at least PHP 5.0 installed on your server in order this cURL function to work.
So now that you know what this functions do, we should first create the links to the servers from were we wanna get info. I will assume that we wanna get information from 3 servers simultaneous:
$list[1] = "http://www.example1.com"; $list[2] = "ftp://example.com"; $list[3] = "http://www.example2.com";
After creating the list of links we should initialize the cURL multi handle and adding the cURL handles.
$curlHandle = curl_multi_init(); for ($i = 1;$i <= 3; $i++) $curl[$i] = addHandle($curlHandle,$list[$i]);
Now we should execute the cURL multi handle retrive the content from the sub handles that we added to the cURL multi handle.
ExecHandle($curlHandle); for ($i = 1;$i <= 3; $i++) { $text[$i] = curl_multi_getcontent ($curl[$i]); echo $text[$i]; }
In the end we should release the handles from the cURL multi handle by calling curl_multi_remove_handle and close the cURL multi handle:
for ($i = 1;$i <= 3; $i++)//remove the sub - handles curl_multi_remove_handle($curlHandle,$curl[$i]); curl_multi_close($curlHandle);
Here is the complete code for doing multithreading in php with cURL:
<? //add a url to the handler function addHandle(&$curlHandle,$url) { $cURL = curl_init(); curl_setopt($cURL, CURLOPT_URL, $url); curl_setopt($cURL, CURLOPT_HEADER, 0); curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1); curl_multi_add_handle($curlHandle,$cURL); return $cURL; } //execute the handle until the flag passed // to function is greater then 0 function ExecHandle(&$curlHandle) { $flag=null; do { //fetch pages in parallel curl_multi_exec($curlHandle,$flag); } while ($flag > 0); } $list[1] = "http://www.example1.com"; $list[2] = "ftp://example.com"; $list[3] = "http://www.example2.com"; $curlHandle = curl_multi_init(); for ($i = 1;$i <= 3; $i++) $curl[$i] = addHandle($curlHandle,$list[$i]); ExecHandle($curlHandle); for ($i = 1;$i <= 3; $i++) { $text[$i] = curl_multi_getcontent ($curl[$i]); echo $text[$i]; } for ($i = 1;$i <= 3; $i++)//remove the handles curl_multi_remove_handle($curlHandle,$curl[$i]); curl_multi_close($curlHandle); ?>
Download complete source
Tags: PHP
Posted in Codes, PHP/MYSQL | 1 Comment »
PHP ajax cascading dropdown using MySql
Written by Codes Tips on May 16, 2009 – 5:31 pm -To do cascading drop down in php using mysql we can use AJAX. The name AJAX is from asynchronous JavaScript and XML and it’s a new technique for web development to build rich interactive web application. The power of this technique comes from the fact that it can send to server requests from the client side, in order to not reload the page. The object that is using AJAX to send and retrieve data between server and the client is named XmlHttpRequest.
To build a cascading drop down in php to retrieve data from a mysql server we will first populate a drop down with the results from a first table from a mysql database. The first table is linked with a second table by a field. When we change the drop down we should assign to OnChanging event an Javascript function that will populate the second drop down . The function will create a new XmlHttpRequest object and make a call to other php script, grab data and populate the second drop down. The script that it’s called will fetch the results for that field that was changed.
Watch a demo here:populate drop down using ajax
Download php cascading drop down using mysql
Tags: AJAX, PHP, PHP/MYSQL
Posted in AJAX, Codes, PHP/MYSQL, Scripts | 15 Comments »
Binary search in string array
Written by Codes Tips on May 10, 2009 – 2:04 pm -To search an string into an array of string you can iterate through all the strings one by one and test which is the string that we wanna search. Doing this you will have a complexity of O(n), where n is the number of the strings that array have.
To do search more efficient you should use binary search which have a complexity of O(log2(n)). To use the binary search method in an array of string we assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary search algorithm when you are doing something complex that have a complexity bigger or equal to O(n^2).
So to search a string in an array the algorithm selects the middle element of the array and verify if it is equal to our string. If it is equal it stops, if not it sees if the string is bigger then our string and if it is, it searches in the right part of the array string, if not in left part, applying the same algorithm. So it uses a recursive function to search the string in the array.
We will use the following type of string and declare a variable:
type arraystrings=array[1..1000000] of string; var words:arraystrings;
Here is the binary search algorithm:
function BinSearch(word:string;l:integer;h:integer):integer; begin while (StrIComp(pchar(word),pchar(words[(l+h)div 2]))<>0)and(l<>h) do begin if strIcomp(pchar(word),pchar(words[(l+h)div 2]))>0 then l:=(l+h)div 2+1 else h:=(l+h)div 2-1; end; if l<>h then BinSearch:=(l+h)div 2 else BinSearch:=0; end;
It returns the position in the array where it was found. If not returns 0.
To call it you can use:
position:=BinSearch(word,1,nrwords);
where word is the string we search for and nrwords it’s the number of strings in the array.
Tags: Algorithms, Delphi
Posted in Algorithms, Codes, Delphi | No Comments »
Quicksort array of string
Written by Codes Tips on May 10, 2009 – 1:33 pm -Quicksort it’s an algorithm that it’s very efficient when you wanna sort an array of any type: string, integer, real. I will show you how to sort an array of string, it can be modified easily to sort other types of array.
Quicksort it’s efficient because it’s having a sorting complexity of O(n* log2(n)). An usual sorting algorithm like bubble sort or merge sort it’s taking O(n^2), which it’s very inefficient for array with over 5000 elements.
I will write an implementation of this algorithm in Delphi.
The Quicksort algorithm it’s very similar to divide and conquer algorithm because it splits the array into to sub arrays, sort those sub arrays and put them together after into 1 array sorted. For sorting those array it uses a pivot that it’s positioned in the middle of the array and put in the left, strings that are lower and in the right, the strings that are higher. So for doing this it uses a recursive function because for every sub array divides again in 2 sub array and sort them. So after sorting each sub array , we will have in the final step all the array sorted.
Here is an implementation of Quicksort array of string in Delphi.
First declare a type of array string:
type arraystrings=array[1..100000] of string;
Quicksort algorithm:
procedure QuickSort(var A: arraystrings; Lo, Hi: Integer); procedure Sort(l, r: Integer); var i, j,aux: integer; y,x:string; begin i := l; j := r; x := a[(l+r) DIV 2]; repeat while strIcomp(pchar(a[i]),pchar(x))<0 do i := i + 1; while StrIComp(pchar(x),pchar(a[j]))<0 do j := j - 1; if i <= j then begin y := a[i]; a[i] := a[j]; a[j] := y; i := i + 1; j := j - 1; end; until i > j; if l < j then Sort(l, j); if i < r then Sort(i, r); end; begin Sort(Lo,Hi); end;
Tags: Algorithms, Delphi
Posted in Algorithms, Codes, Delphi | 2 Comments »


















