Reklam

Reklamlar

8 Haziran 2010 Salı

10 PHP code snippets for working with strings

Strings are a very important kind of data, and you have to deal with them daily with web development tasks. In this article, I have compiled 10 extremely useful functions and code snippets to make your php developer life easier.

Automatically remove html tags from a string

On user-submitted forms, you may want to remove all unnecessary html tags. Doing so is easy using the strip_tags() function:

1.$text = strip_tags($input, "");
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Get the text between $start and $end

This is the kind of function every web developer should have in their toolbox for future use: give it a string, a start, and an end, and it will return the text contained with $start and $end.
1.function GetBetween($content,$start,$end){
2.    $r = explode($start, $content);
3.    if (isset($r[1])){
4.        $r = explode($end, $r[1]);
5.        return $r[0];
6.    }
7.    return '';
8.}
Source: http://www.jonasjohn.de/snippets/php/get-between.htm

Transform URL to hyperlinks

If you leave a URL in the comment form of a WordPress blog, it will be automatically transformed into a hyperlink. If you want to implement the same functionality in your own website or web app, you can use the following code:
1.$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
2.$url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Split text up into 140 char array for Twitter

As you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.
01.function split_to_chunks($to,$text){
02.    $total_length = (140 - strlen($to));
03.    $text_arr = explode(" ",$text);
04.    $i=0;
05.    $message[0]="";
06.    foreach ($text_arr as $word){
07.        if ( strlen($message[$i] . $word . ' ') <= $total_length ){
08.            if ($text_arr[count($text_arr)-1] == $word){
09.                $message[$i] .= $word;
10.            } else {
11.                $message[$i] .= $word . ' ';
12.            }
13.        } else {
14.            $i++;
15.            if ($text_arr[count($text_arr)-1] == $word){
16.                $message[$i] = $word;
17.            } else {
18.                $message[$i] = $word . ' ';
19.            }
20.        }
21.    }
22.    return $message;
23.}
Source: http://snipplr.com/view.php?codeview&id=31648

Remove URLs from string

When I see the amount of URLs people try to leave in my blog comments to get traffic and/or backlinks, I think I should definitely give a go to this snippet!
1.$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
Source: http://snipplr.com/view.php?codeview&id=15236

Convert strings to slugs

Need to generate slugs (permalinks) that are SEO friendly? The following function takes a string as a parameter and will return a SEO friendly slug. Simple and efficient!
1.function slug($str){
2.    $str = strtolower(trim($str));
3.    $str = preg_replace('/[^a-z0-9-]/', '-', $str);
4.    $str = preg_replace('/-+/', "-", $str);
5.    return $str;
6.}
Source: http://snipplr.com/view.php?codeview&id=2809

Parse CSV files

CSV (Coma separated values) files are an easy way to store data, and parsing them using PHP is dead simple. Don’t believe me? Just use the following snippet and see for yourself.
1.$fh = fopen("contacts.csv", "r");
2.while($line = fgetcsv($fh, 1000, ",")) {
3.    echo "Contact: {$line[1]}";
4.}
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1

Search for a string in another string

If a string is contained in another string and you need to search for it, this is a very clever way to do it:
1.function contains($str, $content, $ignorecase=true){
2.    if ($ignorecase){
3.        $str = strtolower($str);
4.        $content = strtolower($content);
5.    }
6.    return strpos($content,$str) ? true : false;
7.}
Source: http://www.jonasjohn.de/snippets/php/contains.htm

Check if a string starts with a specific pattern

Some languages such as Java have a startWith method/function which allows you to check if a string starts with a specific pattern. Unfortunately, PHP does not have a similar built-in function.
Whatever- we just have to build our own, which is very simple:
1.function String_Begins_With($needle, $haystack {
2.    return (substr($haystack, 0, strlen($needle))==$needle);
3.}
Source: http://snipplr.com/view.php?codeview&id=2143

Extract emails from a string

Ever wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam ;)
01.function extract_emails($str){
02.    // This regular expression extracts all emails from a string:
03.    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
04.    preg_match_all($regexp, $str, $m);
05. 
06.    return isset($m[0]) ? $m[0] : array();
07.}
08. 
09.$test_string = 'This is a test string...
10. 
11.        test1@example.org
12. 
13.        Test different formats:
14.        test2@example.org;
15.        "test3@example.org">foobar
16.        
17. 
18.        strange formats:
19.        test5@example.org
20.        test6[at]example.org
21.        test7@example.net.org.com
22.        test8@ example.org
23.        test9@!foo!.org
24. 
25.        foobar
26.';
27. 
28.print_r(extract_emails($test_string));
Dipnot
Bu yazı 8 Haziran 2010 Salı günü yazılmıştır. Bulunduğu kategori : ,,,,. Yazdığım yazıları RSS 2.0 sistemini kullanarak takip edebilir, dilerseniz yorum yapabilirsiniz. Unutmadan, Bu yazı sizler tarafından tam tamına defa okunmuştur.

Hiç yorum yok:

Yorum Gönder

Sitemizi ziyaret ettiğiniz için teşekkür ederiz


Php Dersleri

ebook library