<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Aditya Kothadiya&#039;s Blog &#187; Programming</title>
	<atom:link href="http://adityakothadiya.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://adityakothadiya.com</link>
	<description>Entrepreneurship, programming, design, productivity, books, philosophy and more.</description>
	<lastBuildDate>Sun, 16 May 2010 16:20:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>All You Need to Know to Master The Vim Editor</title>
		<link>http://adityakothadiya.com/2009/10/all-you-need-to-know-to-master-the-vim-editor/</link>
		<comments>http://adityakothadiya.com/2009/10/all-you-need-to-know-to-master-the-vim-editor/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 13:26:31 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[hacks]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[vi]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=489</guid>
		<description><![CDATA[I use Vim Editor every single day and really like it. Few years ago when I started learning Vim editor, I found it very daunting to learn all those commands and tricks, and then remember those commands, and most importantly &#8211; apply those commands for day-to-day tasks. Over the past years, I learned a lot, [...]]]></description>
			<content:encoded><![CDATA[<p>I use Vim Editor every single day and really like it. Few years ago when I started learning Vim editor, I found it very daunting to learn all those commands and tricks, and then remember those commands, and most importantly &#8211; apply those commands for day-to-day tasks. Over the past years, I learned a lot, step by step. But I&#8217;m still not there yet. I&#8217;m not master yet. I&#8217;ve seen few my colleagues doing magic with Vim, which I can just appreciate but not understand and apply. I always wanted to learn more tricks and tips and master the editing with Vim. Finally I found some great articles compiled together to master Vim editor on this blog post &#8211; <a href="http://www.joelhughes.co.uk/blog/2009/10/vim-is-a-great-text-editor/">Vim is a great text editor</a>.</p>
<p>Following are the useful links that you can peruse to master the Vim Editor -</p>
<ul>
<li>Find the appropriate version of <a href="http://www.vim.org/download.php" target="_blank">Vim for your OS and install</a>.</li>
<li>Start learning the ropes with these tutorials:
<ul>
<li><a href="http://www.eecs.harvard.edu/%7Ecduan/technical/vi/vi-1.shtml" target="_blank">Using Vi/Vim: A Brief Tutorial</a></li>
<li><a href="http://jmcpherson.org/editing.html" target="_blank">Efficient Editing With vim</a></li>
<li><a href="http://jmcpherson.org/windows.html" target="_blank">Splits and multi-file editing</a></li>
<li><a href="http://www.tuxfiles.org/linuxhelp/vimcheat.html" target="_blank">The Vim commands cheat sheet &#8211; 1.2</a></li>
<li><a href="http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html" target="_blank">Graphical cheat sheet</a></li>
<li><a href="http://vim.wikia.com/wiki/Best_Vim_Tips" target="_blank">Vim Tips wiki</a></li>
</ul>
</li>
<li>Vim is very customizable, the settings are stored in the <em>vimrc</em> file which resides in the install’s directory:
<ul>
<li><a href="http://groups.google.com/group/vim_use/msg/355844152db8fcb3" target="_blank">Select colour scheme and font</a></li>
<li><a href="http://tedlogan.com/techblog3.html" target="_blank">Secrets of tabs in vim (set indent type and depth)</a></li>
<li><a href="http://jmcpherson.org/vimrc.html" target="_blank">vimrc tips</a></li>
<li><a href="http://www.vi-improved.org/vimrc.php" target="_blank">Example .vimrc</a></li>
<li><a href="http://www.catonmat.net/blog/vim-plugins-surround-vim/">Vim plugins</a></li>
</ul>
</li>
</ul>
<p>I found these links very useful, and I hope you&#8217;ll find them useful too. You may not be able to digest this all information at once. You&#8217;ll have to learn few things, and then practice it, and then master it. But now you have all the resources to master Vim at one place!</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/10/all-you-need-to-know-to-master-the-vim-editor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automating Your MySQL Database Backup On Media Temple’s Grid-Server</title>
		<link>http://adityakothadiya.com/2009/05/automating-your-mysql-database-backup-on-media-temple%e2%80%99s-grid-server/</link>
		<comments>http://adityakothadiya.com/2009/05/automating-your-mysql-database-backup-on-media-temple%e2%80%99s-grid-server/#comments</comments>
		<pubDate>Mon, 25 May 2009 18:26:00 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=447</guid>
		<description><![CDATA[Let me admit this &#8211; I did not backup the Tweeght&#8217;s database until today. Somehow I kept procrastinating it for no reason. Since Tweeght is growing consistently, it was crucial for me to backup its database on daily basis and prepare myself from loosing all the crucial data in some sort of catastrophic event.
I use [...]]]></description>
			<content:encoded><![CDATA[<p>Let me admit this &#8211; I did not backup the <a href="http://tweeght.com" target="_blank">Tweeght</a>&#8217;s database until today. Somehow I kept procrastinating it for no reason. Since Tweeght is growing consistently, it was crucial for me to backup its database on daily basis and prepare myself from loosing all the crucial data in some sort of catastrophic event.</p>
<p>I use Media Temple&#8217;s Grid-Server for Tweeght. MT has good knowledge base article on &#8211; <a href="http://kb.mediatemple.net/questions/129/How+can+I+Backup+and+Restore+a+MySQL+database%3F" target="_blank">How can I Backup and Restore a MySQL database?</a>.</p>
<p>But this article just mentions about how to backup your database for once. I wanted to automate this backup process on daily basis. So I Googled a little-bit, and came across <a href="http://www.websitepublisher.net/article/mysql-backup/" target="_blank">this wonderful script</a>. So I took that script, updated it for MT&#8217;s Grid-Server infrastructure, and now I&#8217;m all set within 20 minutes to take daily backups of my crucial databases.</p>
<p><strong>Here are the steps I followed:</strong></p>
<p>1. Go to /data directory in your account. I preferred this over /domains directory because this is accessible only by you and not by public. You don&#8217;t want the public to accidentally access dump of your database.</p>
<p>2. Create /db_backup directory. Go to /db_backup directory and create three new directories &#8211; /scripts , /daily and /recent.</p>
<p>3. Go to /scripts directory and open up your favorite editor. Copy and paste following code -</p>
<pre class="brush: plain;">
#!/bin/bash
# Set a value that we can use for a datestamp
DATE=`date +%Y-%m-%d`
# Our Base backup directory
BASEBACKUP=&quot;/home/XXXXX/data/db_backup/daily&quot;

for DATABASE in `cat /home/XXXXX/data/db_backup/scripts/db_list.txt`
do
# This is where we throw our backups.
FILEDIR=&quot;$BASEBACKUP/$DATABASE&quot;

# Test to see if our backup directory exists.
# If not, create it.
if [ ! -d $FILEDIR ]
then
mkdir -p $FILEDIR
fi

echo -n &quot;Exporting database:  $DATABASE&quot;
mysqldump --add-drop-table -h internal-db.sXXXXX.gridserver.com -udbXXXXX -pPASSWORD $DATABASE | gzip -c -9 &gt; $FILEDIR/$DATABASE-$DATE.sql.gz
echo &quot;      ......[ Done Exporting to local backup, now exporting for remote backup] &quot;
cp $FILEDIR/$DATABASE-$DATE.sql.gz /home/XXXXX/data/db_backup/recent/$DATABASE.sql.gz
echo &quot;      .......[Done]&quot;
done

# AutoPrune our backups.  This will find all files
# that are &quot;MaxFileAge&quot; days old and delete them.
MaxFileAge=4
find $BASEBACKUP -name '*.gz' -type f -mtime +$MaxFileAge -exec rm -f {} \;
</pre>
<p>4. Change few things in above code -</p>
<ul>
<li>Replace all the instances of &#8216;XXXXX&#8217; with your gridserver account number.</li>
<li>Replace &#8216;PASSWORD&#8217; with your SSH password</li>
</ul>
<p>5. Now save this file as something like &#8216;db_backup.sh&#8217;</p>
<p>6. Open up your editor one more time, and write the names of databases you want to back up on each single line -</p>
<pre class="brush: plain;">
dbXXXXX_proj1
dbXXXXX_proj2
</pre>
<p>7. Now save this file as something like &#8216;db_list.txt&#8217;</p>
<p>8. Basically, the script pulls a list of databases to be backed up from a file called db_list.txt, this file takes 1 database name per line. It then exports the database and compresses, then saves it with a date-stamped filename to a directory called ../daily/&lt;db_name&gt;/.</p>
<p>Then, the script copies a non-date-stamped filename to a directory called ../recent/, thus overwriting the previous file stored there.</p>
<p>Finally it goes through the daily directory structure and deletes any files older than 4 days.</p>
<p>9. Now you can test your backup script by running following command -</p>
<pre class="brush: plain;">
./db_backup.sh
</pre>
<p>10. The script will echo out some progress messages. If no error message, then hopefully your databases should be backed up.</p>
<p>To see if it was successful execution, go to ../daily directory. You will see directories created with &lt;db_name&gt; names. Under these directories, you&#8217;ll see compressed version of sql dumps. Similarly, go to ../recent directory, and you&#8217;ll see the similar compressed version of sql dump.<br />
To automate this backup process, go to your MediaTemple&#8217;s admin section of your primary domain and click the &#8220;Cron Jobs&#8221; link.</p>
<p>11. Click on the &#8216;Add a new cron job&#8217; button.</p>
<p>12. Add your email address in the &#8220;Notification Email&#8221; field. This will send you emails whenever the cron job runs and will let you know if it was successful or not.</p>
<p>13. Also add path of your script in the &#8220;Command or script to execute&#8221; field. Enter: /home/XXXXX/data/db_backup/scripts/db_backup.sh. Again, replace &#8216;XXXXX&#8217; with your gridserver account number.</p>
<p>14. On the same page, you can specify how often you&#8217;d like your script to run. This entire section is up to you requirements. I&#8217;ve set mine to run daily at 3:00 AM when traffic on my site is slower.</p>
<p>15. Click Save and you&#8217;re all set to backup your databases on daily basis!</p>
<p>I hope this will be useful to you. If you see any issues, please let me know in the comment section.</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/05/automating-your-mysql-database-backup-on-media-temple%e2%80%99s-grid-server/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>The PHP Benchmark</title>
		<link>http://adityakothadiya.com/2009/04/the-php-benchmark/</link>
		<comments>http://adityakothadiya.com/2009/04/the-php-benchmark/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 18:00:01 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[speed]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=425</guid>
		<description><![CDATA[I just stumbled upon a website called PHP Benchmark. It&#8217;s a great resource to learn PHP tips for improving performance and speed. These are not advanced tips, but rather very simple tips that we generally don&#8217;t pay attention to in our day-to-day programming.
Here is one example -
Is it worth the effort to calculate the length [...]]]></description>
			<content:encoded><![CDATA[<p>I just stumbled upon a website called <a href="http://www.phpbench.com/" target="_blank">PHP Benchmark</a>. It&#8217;s a great resource to learn PHP tips for improving performance and speed. These are not advanced tips, but rather very simple tips that we generally don&#8217;t pay attention to in our day-to-day programming.</p>
<p>Here is one example -</p>
<p><strong>Is it worth the effort to calculate the length of the loop in advance?</strong></p>
<p>E.g. Should we use</p>
<pre class="brush: php;">

for ($i = 0; $i &lt; $size; $i++)
</pre>
<p>instead of</p>
<pre class="brush: php;">

for ($i = 0; $i &lt; sizeof($arr); $i++)
</pre>
<p>The performance result for a loop with 1000 keys with 1 byte values is as below -</p>
<blockquote><p><strong>With pre calc &#8211; count():</strong> Total time: 229 µs<br />
<strong>Without pre calc &#8211; count():</strong> Total time: 99702 µs<br />
<strong>With pre calc &#8211; sizeof(): </strong>Total time: 235 µs<br />
<strong>Without pre calc &#8211; sizeof():</strong> Total time: 99610 µs</p></blockquote>
<p>So it&#8217;s very clear that calculating the length of array in advance is way faster than calculating it in the loop.</p>
<p>I hope you&#8217;ll find other tips from PHP Benchmark website very useful too.</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/04/the-php-benchmark/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Verifying Twitter account credentials using Symfony validator in PHP</title>
		<link>http://adityakothadiya.com/2009/04/verifying-twitter-account-credentials-using-symfony-validator-in-php/</link>
		<comments>http://adityakothadiya.com/2009/04/verifying-twitter-account-credentials-using-symfony-validator-in-php/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 04:47:31 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[symfony]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=418</guid>
		<description><![CDATA[If you&#8217;re using Symfony &#8211; a PHP&#8217;s MVC framework to develop your web application, and if your application interacts with Twitter, and if you need Twitter user&#8217;s credentials to access his or her data from Twitter, then this might be useful to you.
Here is a simple Twitter class -

&#60;?php
class Twitter {
private $credentials;

function Twitter($username, $password) {
$this-&#62;credentials [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re using <strong><a href="http://www.symfony-project.org" target="_blank">Symfony</a> &#8211; a PHP&#8217;s MVC framework</strong> to develop your web application, and if your application interacts with <a href="http://twitter.com" target="_blank">Twitter</a>, and if you need Twitter user&#8217;s credentials to access his or her data from Twitter, then this might be useful to you.</p>
<p><strong>Here is a simple Twitter class -</strong></p>
<pre class="brush: php;">
&lt;?php
class Twitter {
private $credentials;

function Twitter($username, $password) {
$this-&gt;credentials = sprintf(&quot;%s:%s&quot;, $username, $password);
}

function verifyCredentials($format = NULL) {
$api_call = sprintf(&quot;http://twitter.com/account/verify_credentials%s&quot;, ($format != NULL) ? sprintf(&quot;.%s&quot;, $format) : NULL);
return $this-&gt;APICall($api_call, true);
}

private function APICall($api_url, $require_credentials = false, $http_post = false) {
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $api_url);

if ($require_credentials) {
curl_setopt($curl_handle, CURLOPT_USERPWD, $this-&gt;credentials);

}
if ($http_post) {
curl_setopt($curl_handle, CURLOPT_POST, true);
}
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
$twitter_data = curl_exec($curl_handle);

curl_close($curl_handle);
return $twitter_data;
}
}
?&gt;
</pre>
<p><strong>Then here is the simple action to handle form &#8211; </strong></p>
<pre class="brush: php;">
public function executeTwitterLogin()
{
if ($this-&gt;getRequest()-&gt;getMethod() == sfRequest::POST)
{
$username = $this-&gt;getRequestParameter('username');
$password =  $this-&gt;getRequestParameter('password');

// Your business logic here...
}
}
</pre>
<p><strong>Here is the action to handle error for TwitterLogin action &#8211; </strong></p>
<pre class="brush: php;">
public function handleTwitterLogin()
{
return sfView::SUCCESS;
}
</pre>
<p><strong>Here is a simple template with the form asking for the Twitter login credentials -</strong></p>
<pre class="brush: php;">
&lt;?php use_helper('Validation', 'Form') ?&gt;

&lt;?php echo form_tag('@twitter_login') ?&gt;

&lt;p&gt;Please enter your Twitter account's login credentials below.&lt;/p&gt;

&lt;?php echo form_error('username') ?&gt;
&lt;label for=&quot;username&quot;&gt;Twitter Username:&lt;/label&gt;
&lt;?php echo input_tag('username', $sf_params-&gt;get('username')) ?&gt;

&lt;?php echo form_error('password') ?&gt;
&lt;label for=&quot;password&quot;&gt;Twitter Password:&lt;/label&gt;
&lt;?php echo input_password_tag('password') ?&gt;

&lt;?php echo submit_tag('Login') ?&gt;
&lt;/form&gt;
</pre>
<p><strong>Here is the twitterLogin.yml validator file &#8211; </strong></p>
<pre class="brush: php;">
methods:
post: [username, password]

names:
username:
required:     true
required_msg: Your Twitter Username is required.
validators:   userValidator

password:
required:     true
required_msg: Your Twitter Password is required.

userValidator:
class:        twitterLoginValidator
param:
password:    password
</pre>
<p><strong><br />
And finally, here is the custom class which is extended from sfvalidator for authenticating Twitter login details.</strong></p>
<pre class="brush: php;">
&lt;?php
class myTwitterLoginValidator extends sfValidator
{
public function initialize($context, $parameters = null)
{
// initialize parent
parent::initialize($context);

// set defaults
$this-&gt;setParameter('error', 'Your Twitter account credentials are incorrect.');
$this-&gt;getParameterHolder()-&gt;add($parameters);

return true;
}

public function execute(&amp;amp;$value, &amp;amp;$error)
{
$password_param = $this-&gt;getParameter('password');
$password = $this-&gt;getContext()-&gt;getRequest()-&gt;getParameter($password_param);

$username = $value;

// Verify Twitter Credentials
$twitter = new Twitter($username, $password);
$resp_xml = $twitter-&gt;verifyCredentials('xml');
$resp_xml = simplexml_load_string($resp_xml);

$resp_username = $resp_xml-&gt;screen_name;
$verified = strcasecmp($username, $resp_username); // returns 0 if they are equal

if ($verified === 0)
return true;

$error = $this-&gt;getParameter('error');
return false;
}
}
?&gt;
</pre>
<p>I hope you&#8217;ll find this useful. Let me know in the comments section if you see any issue while using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/04/verifying-twitter-account-credentials-using-symfony-validator-in-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Generate sequential strings for URL addresses using PHP</title>
		<link>http://adityakothadiya.com/2009/01/generate-sequential-strings-for-url-addresses-using-php/</link>
		<comments>http://adityakothadiya.com/2009/01/generate-sequential-strings-for-url-addresses-using-php/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 14:30:54 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[strings]]></category>
		<category><![CDATA[URL]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=352</guid>
		<description><![CDATA[I&#8217;m working on an interesting project right now, and for this project, I wanted to generate URLs with sequential alphabetic sequence as opposed to using numeric IDs. Using alphabetic string allows me to use short URL addresses with many URL combinations. E.g. If I use numeric indexes, then I can only have 10 possibilities to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on an interesting project right now, and for this project, I wanted to generate URLs with sequential alphabetic sequence as opposed to using numeric IDs. Using alphabetic string allows me to use short URL addresses with many URL combinations. E.g. If I use numeric indexes, then I can only have 10 possibilities to represent http://abc.com/N, where N= 0 to 9. But instead, if I use alphabetic character, I have 26 possibilities where N= a, b, c to z. I don&#8217;t want to add usability issues by using both upper and lower cases of alphabets, so I&#8217;ll stick to lower case addresses only.</p>
<p>So I needed a function which will generate sequential alphabetic strings for URL address based on incremental numbers. So I coded up following function:</p>
<pre class="brush: php;">
function getAlphaString($num)
{
  $alpha = '';
  while($num &gt;= 1) {
    $num = $num - 1;
    $alpha = chr(($num % 26)+97) . $alpha;
    $num = $num / 26;
  }
  return $alpha;
}
</pre>
<p>Use this in a for{} loop, and it will give you sequential strings. Or call with individual numbers as shown below, and it will return you appropriate alphabetic string.</p>
<pre class="brush: php;">
echo getAlphaString(5) . &quot;\n&quot;;
echo getAlphaString(500) . &quot;\n&quot;;
echo getAlphaString(500000) . &quot;\n&quot;;
echo getAlphaString(50000000) . &quot;\n&quot;;
</pre>
<p>And it produced following output:</p>
<pre class="brush: php;">
e
sf
abkpt
dejtlx
</pre>
<p>Hope you&#8217;ll find this function  useful in one of your applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/01/generate-sequential-strings-for-url-addresses-using-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Splitting strings in PHP using explode Vs split functions</title>
		<link>http://adityakothadiya.com/2009/01/splitting-strings-in-php-using-explode-vs-split-functions/</link>
		<comments>http://adityakothadiya.com/2009/01/splitting-strings-in-php-using-explode-vs-split-functions/#comments</comments>
		<pubDate>Fri, 16 Jan 2009 16:38:51 +0000</pubDate>
		<dc:creator>Aditya</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[explode]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[split]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://adityakothadiya.com/?p=337</guid>
		<description><![CDATA[Splitting strings into an array is nothing new and is pretty easy using the explode function if your input string pattern is consistent. But if your input string pattern is a little less consistent, then using the split function makes it a lot easier than doing some post-processing on array elements produced by the explode [...]]]></description>
			<content:encoded><![CDATA[<p>Splitting strings into an array is nothing new and is pretty easy using the <a href="http://us3.php.net/explode" target="_blank">explode</a> function if your input string pattern is consistent. But if your input string pattern is a little less consistent, then using the <a href="http://us3.php.net/split" target="_blank">split</a> function makes it a lot easier than doing some post-processing on array elements produced by the explode function.</p>
<p>Here is an example:</p>
<p>I have an input field where I ask user to enter her friends&#8217; email addresses to invite them. I instruct user to use commas to separate multiple email addresses. But user will not necessarily enter all email addresses with consistent pattern. The input string may not contain any spaces, or may contain optional spaces before or after actual email addresses. For example:</p>
<pre class="brush: php;">
$recipient_email_list = &quot;abc@example.com, def@example.com,ghi@example.com , jkl@example.com , mno@example.com&quot;;
$recipient_emails = explode(',', $recipient_email_list);

//Echo with '|' delimiter to see the spaces before and after email address:

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}
</pre>
<p>The output is as below:</p>
<pre class="brush: php;">
abc@example.com| def@example.com|ghi@example.com | jkl@example.com | mno@example.com|
</pre>
<p>In above example, few exploded strings have additional spaces. So you need to do post-processing on the exploded array as below:</p>
<pre class="brush: php;">
$i=0;
foreach ($recipient_emails as $recipient_email)
{
  $found = preg_match('/ /', $recipient_email);
  if($found)
  {
    $recipient_emails[$i]= trim($recipient_email);
  }
  $i++;
}

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}
</pre>
<p>Then the output is as below:</p>
<pre class="brush: php;">
abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|
</pre>
<p>But there is another easy way to avoid this extra lines of post-processing code. Use split function as below:</p>
<pre class="brush: php;">
$recipient_emails = split(' *, *', $recipient_email_list);

foreach ($recipient_emails as $recipient_email)
{
  echo $recipient_email.'|';
}
</pre>
<p>Then the output is as below:</p>
<pre class="brush: php;">
abc@example.com|def@example.com|ghi@example.com|jkl@example.com|mno@example.com|
</pre>
<p>In above example, split function actually splits an input string into an array by regular expression &#8216; *, *&#8217; i.e. split by zero or more spaces after or before the comma character.</p>
<p>I hope you will find this useful. If you have more inputs or questions, then please share in comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://adityakothadiya.com/2009/01/splitting-strings-in-php-using-explode-vs-split-functions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
