10 đoạn code PHP hữu ích khi xử lý chuỗi

Hiện tại, vì công việc quá bận rộn nên mình không còn thời gian để post bài và duy trì nội dung cho blog nữa. Do đó tại thời điểm này, mình quyết định ngừng phát triển blog. Mọi bài viết sẽ vẫn được lưu trữ và mình sẽ cố gắng hỗ trợ tất cả các bạn khi có comment hỏi. Cảm ơn các bạn đã ủng hộ blog suốt thời gian qua !

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:

$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.

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

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:

$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$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.

function split_to_chunks($to,$text){
    $total_length = (140 - strlen($to));
    $text_arr = explode(" ",$text);
    $i=0;
    $message[0]="";
    foreach ($text_arr as $word){
        if ( strlen($message[$i] . $word . ' ') <= $total_length ){
            if ($text_arr[count($text_arr)-1] == $word){
                $message[$i] .= $word;
            } else {
                $message[$i] .= $word . ' ';
            }
        } else {
            $i++;
            if ($text_arr[count($text_arr)-1] == $word){
                $message[$i] = $word;
            } else {
                $message[$i] = $word . ' ';
            }
        }
    }
    return $message;
}

Source: http://www.phpsnippets.info/split-text-up-into-140-char-array-for-twitter

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!

$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!

function slug($str){
    $str = strtolower(trim($str));
    $str = preg_replace('/[^a-z0-9-]/', '-', $str);
    $str = preg_replace('/-+/', "-", $str);
    return $str;
}

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.

$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";
}

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:

function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}

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:

function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);
}

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 ;)

function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$test_string = 'This is a test string...

        test1@example.org

        Test different formats:
        test2@example.org;
        <a href="test3@example.org">foobar</a>
        <test4@example.org>

        strange formats:
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org

        foobar
';

print_r(extract_emails($test_string));

Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm
 

Web Design Technology blogs [ itdl ] Auto Backlink

HomeBlog ArchiveServicesLink2MeContactSubmit your PostPost RSS

Copyright © 2012 [ itdl ] Just for Share. Designed by Ngoc Luong - Freelancer

Best view in Chrome 11+, Firefox 5+ with resolution 1024 x 768 pixel. Powered by Blogger.