Archive for the ‘PHP’ category

Regular Expression to Find All Mentioned Names by ‘@’

December 12th, 2009

Most of the time we use ‘@’ to mention someone’s name in email thread, forum, etc. How about to find those mentioned names using PHP regular expression? Let’s consider the following text.

“Hey @Junal how about going for a vacation to @Srimangal? @Jewel said it’s an awesome place”
We will find all names that is mentioned by @ here. So let’s write the pattern first.

$pattern = “/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/”;

See, first portion of the pattern is optional, some one can start your name @junal or hey @junal right. And then we are matching with ‘@’ separating them from @ sign. Rest portion of the patter is quite easy, as we can keep text after the name (I.e @junal you suck)

Ok, now let’s use the php preg_match() function to find the matches. If we find the matched it will return 1 else 0.

$pattern = "/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/";
$str = "Hey @Junal hey how are you?";
preg_match($pattern, $str, $matches);
print_r($matches);
//Output : 
Array
(
    [0] => Hey @Junal hey how are you?
    [1] => Junal
    [2] => hey how are you?
)

So, if we want to find first matched name then it’s pretty straight forward to get it from $matches[1]
but what if we want to find multiple name from a text? Well, then we have to search $matches[2] if there is anymore mentioned name wit @ right?… let’s do it this way…

do {
   preg_match($pattern, $matches[2], $more_matches);
   $name_list[$counter++]  = $more_matches[1];
   $count = count($more_matches);
   $matches[2]=$more_matches[($count-1)];
   $more_matches = "";
   } while($count>=3);

this above code might be confusing. So let’s see the complete function that returns us an array of names that are mentioned by ‘@’ and well, we will also remove the duplicate names.

< ?php
/*
 * isn't the name self explanatory ?
 */
function giveme_names_from_at($str) {
    $pattern = "/^(?:[a-zA-Z0-9?. ]?)+@([a-zA-Z0-9]+)(.+)?$/";
    $str = trim($str);
    preg_match($pattern, $str, $matches);;
    if($matches) {
        $counter = 0;
        $name_list = array();
        $name_list[$counter++] = $matches[1];
 
        do {
            preg_match($pattern, $matches[2], $more_matches);
            $name_list[$counter++]  = $more_matches[1];
            $count = count($more_matches);
            $matches[2]=$more_matches[($count-1)];
            $more_matches = "";
        } while($count>=3);
 
        if(!empty($name_list)) {
            $all_names = array();
            $i = 0;
            foreach ($name_list as $key => $value) {
                if (!is_null($value) && (!in_array($value, $all_names))) {
                    $all_names[$i] = $value;
                    $i++;
                }
            }
        }
        return $all_names;
    }
}
 
//Example 
 
$str = "Hey @Junal how about going for a vacation to @Srimangal? @Jewel said it's an awesome place";
$names = giveme_names_from_at($str)
print_r($names);
 
//Output: 
Array
(
    [0] => Junal
    [1] => Srimangal
    [2] => Jewel
)
?>

Ok well, output shows what we needed. But using regular expression is not always a good idea as it’s slower than standard string manipulation functions. How would you like to find these answers without using RE? Or can we improve this pattern to make It smarter?

Optimize All JPEG Images With Jpegtran Utility

July 15th, 2009

I was looking for an utility that compress an image without losing the current quality of it. According to Yslow guideline it says “Jpegtran does lossless JPEG operations such as rotation and can also be used to optimize and remove comments and other useless information (such as EXIF information) from your images. ”

Installing (Linux)

  • Download jpegtran library from here

  • Unpack and paste the executable file under /usr/bin folder.

  • Open the command-line and try this > jpegtran -h command to check if its working

Options:

-Optimize

Perform optimization of entropy encoding parameters.

-Progressive

Create progressive JPEG file.

-Restart N

Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if “B” is attached to the number.

-Scans file

Use the scan script given in the specified text file.

Command example:

> jpegtran -copy none -rotate 270 -optimize /home/junal/Desktop/Junal/DSC_4164.JPG > /home/junal/Desktop/Junal/DSC_4166.JPG

it reduced the current size 3.4 MB to 3.2MB, keeping the same quality of the image, bingo!

The jpegtran command-line program is useful to:

  • Optimize the Huffman coding layer of a JPEG file to increase compression,
  • Convert between progressive and non-progressive JPEG formats,
  • Eliminate non-standard application-specific data inserted by some image programs, or
  • To perform certain transformations on a file, such as:
    • grayscaling,
    • rotating and flipping (within certain limits), and
    • cropping

to make all these tasks easier you can use imgopt which does all these above easier way. You just need to download the library file and paste it in the right path , now you just have to show the image folder that you want to optimize. And you can do it for both JPEG and PNG file as well.

Installing (Windows)

Windows users can get an executable file from here http://sylvana.net/jpegcrop/

Reference: http://en.wikipedia.org/wiki/Jpegtran

Presenting “Developing Facebook Application” at PHPExperts Semianr 2009

May 17th, 2009

Today, I was really honored to present “how to develop facebook application” at PHPExperts Semianr 2009. Indeed, that was a great experience for me to be in front of bunch of talent guys from whole Bangladesh. Though, it was not possible to show all important points/notes/stories by one presentation at a time, so my target audience were those who were willing to start developing facebook application and my aim was to make it as simple as possible, so that they can start…..

I dont know how successful I was for this…but I will be really happy if I see people are getting interest about developing facebook application.

Personally, I’m very much thrilled after this seminar, because I met lots of people I know from twitter, friendfeed or facebook. Now, i’m pretty sure we have this natural bonding between us. I would like to thank everybody whom I met or who enjoyed my presentation. Your suggestions are always welcome to me. If I ever get any chance again in any other seminar, I will try to talk about advance facebook application developing.

Thanks to all PHPExperts!

DOWNLOAD the source codes of the example i showed in the presentation

Check out the reference from here

Facebook Chat Invite API to Increase The Application Users.

March 13th, 2009

Over the last few days, we have seen some major changes on Facebook developer platform which will increase the application developers to engage more users with their applications. I will try to write on them one by one in near future whenever I get time. Today, i’m going to discuss “Chat Invite API” with an example and I will also focus on area(s) how we can use this API to get more users attention.

Chat invite API Enables your users to initiate Facebook Chat with their friends from within your applications. Great! Let’s give this responsibility to users to bring their friends in our application.

Three main attributes of this API are..

  • msg (required)
  • condensed
  • exclude_ids

an example could be like the following..

<fb:chat-invite msg="let's play a game!" condensed="false" exclude_ids="1,2,3"/>

2 things are very important here, “msg” that comes in the chat input box when you select an online friend from the list, so be sure that you put something related to your application. Setting up the application URL will be right idea along with some text.

I.e :

 msg ="Come join me! <?=$base_url;?>"

another attribute is “exclude_id”, let’s exclude those who haven’t added this application and idle. So that we will show those users who have not added our application and who are idle. Let’s look at the complete example that does this job for us.

<?php 
include_once("config.php");
$users = $facebook->api_client->fql_query("SELECT uid FROM user WHERE is_app_user = 1 and uid IN (SELECT uid2 FROM friend WHERE uid1 = {$fbuser})");
/*
 * Now, let's make these ids comma seperated (1,2,3)
 */
$arFriends = "";
    // Build an delimited list of users...
    if ($users){
        $arFriends .= $users[0]["uid"];
        for ( $i = 1; $i &lt; count($users); $i++ )    {
            if ( $arFriends != "" )        $arFriends .= ",";
            $arFriends .= $users[$i]["uid"];
        }
    }
?>
//now place this code where you want to show your chat invite box.
<fb:js-string var="chatInvite">  <fb:chat-invite msg="Come join me! <?=$base_url;?>" condensed="true" exclude_ids="<?=$arFriends;?>"/> </fb:js-string>
    <div id="chat_invite_container"></div>
<script> document.getElementById('chat_invite_container').setInnerFBML(chatInvite); </script>

Chat with friends from Canvase Page

Chat with friends from Canvase Page

Thats it! Now, we can allow users to talk to their friends directly from your application.

Reference : http://wiki.developers.facebook.com/index.php/Fb:chat-invite

A Comparative Study on Elgg, Drupal and Wordpress!

November 22nd, 2008

Elgg is known for a social networking application, Drupal is known as a Content Management System and Wordpress is known for blogging. But with all these three applications you can develop a huge community based application.

Purpose of this comparative study was to find out a better application to develop a community based application. To do that, I considered few simple things as follows.

  • How easy to create a plug-in/widget/module

  • Number of available built-in plug-ins

  • Documentation and

  • Themes

and followings are the results that I have got after installing them, playing with them and studying on them..

Elgg:

Creating a plug-in : As usual, nothing too complicated.

Available plug-ins: There around 200 plug-ins found and most common plug-ins are there.

Documentation : They have good documentations on their core developments. But its not vastly described

Themes : There are only few themes found. This is bad side of these applications that it doesn’t have too many built-in themes.

Summary : A social networking application. Installation is very easy, same for widget and plug-in. mainly focused on social networking to connect friends and make a common place for all friends. It has got all plug-ins and widgets that required creating a social application. Problem is there are not too much options or built-in features and customizations will be required in most of the cases. Although creating plug-ins and widgets will not be a big deal. It has very good drag drop options and easy installations system. Community is not that big in fact! And main problem they got only few built-in themes!

Drupal:

Creating a plug-in : Ain’t that easy as they don’t inspire you to code. What we can do is…we can install the related module and we can customize it! Or creating a module will be a little bit complected.

Available plug-ins: A lot! Saw almost all needed features which they called MODULE.

Documentation : They have PDF version of the document. And its really cool.

Themes : There are sufficient Themes available in Drupal official site and in third party site but developing a Drupal will be a little be tricky. It has to go through some enabling/disabling stuff and it has to go through some API calls as well.

Summary : Mainly a CMS but they also call it CMF. So this Content management Framework supposed to allow to customize the code and make it on our own way. It has some problem on installations. Like php.ini has default memory limit 8M but Drupar required 16M. And they also have some other complication over installations. But, after all it can be a nice choice for community based application.

Wordpress:

Creating a plug-in : Not a big deal at all! In fact, this is one of the easiest among others.

Available plug-ins: Thousands by hundreds of developers!

Documentation : Wordpress got best documentations among all these names I mentioned.

Themes : Really easy!

Summary : Wordpress is popular for its huge community and the flexibility. Their documentation is simply awesome. Creating plug-ins and theme are easier than any other one I’m comparing here. It has got all the necessary plug-ins and widgets they any kind of community based application needs.

In My Humble Opinion : Wordpress is the winner :)

Get Adobe Flash playerPlugin by wpburn.com wordpress themes