10 PHP code snippets when working with strings (Strings)

View: 605    Dowload: 0   Comment: 0   Post by: hanhga   Category: References   Fields: Other

9 point/4 review File has been tested

Strings also called chain, is one of the important data type and is used most commonly. The master in handling chain will help a lot for you in the web programming later. In this article, I would like to share 10 string processing code that may use the information you will need in the future.

10-php-code-snippets-khi-lam-viec-voi-chuoi-strings

Automatically removes html tags from a string

When the user submits the form, you can easily remove unnecessary html tags using strip_tags function:

1
$text = strip_tags($input, "");

Get the text between $ start and $ end

This is probably a function that any future web developer will also be required to use. It will help you get the text in between 2 other places.

1
2
3
4
5
6
7
8
function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}

Cách sử dụng như sau :

1
2
3
GetBetween('foo test bar', 'foo', 'bar');
 
// --> returns ' test ';

Remove URLs from a string

When you need to remove every link in the chain, you just need to use the following code:

1
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);

Converting strings into slugs

You want to generate slugs (permalinks) for SEO friendly? from the article title. The following simple code will help you do this:

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

And you used to use as follows:

1
2
3
$title = " 10 PHP code snippets ":
$slugs = slug($title);
// xuất ra màn hình sẽ là :  10-php-code-snippets

Parse CSV files

CSV (Coma Separated Values) files are an easy way to store data. The following code will help you to analyze the CSV file.

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

Search one string from another string

The following code will return the value "true" if the search string is found, and otherwise it will return the value to "false".

1
2
3
4
5
6
7
function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}

Filter the emails from a string

The code below will help you retrieve all email filters in a chain.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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));

Generate random string

The following code suitable for creating captcha

1
2
3
4
5
6
7
8
function generate_rand($l){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  srand((double)microtime()*1000000);
  for($i=0; $i<$l; $i++) {
      $rand.= $c[rand()%strlen($c)];
  }
  return $rand;
 }

Way Point chain breaker.

The following code will help you cut the string from another string with specified length, and in particular paragraph are taken will only be cut at the line breaks so that it does not make the chain being interrupted.

01
02
03
04
05
06
07
08
09
10
11
12
13
function myTruncate($string, $limit, $break=".", $pad="...") {
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit)
        return $string;
 
    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {
        if($breakpoint < strlen($string) - 1) {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }
    return $string;
}

And to use, you declare as follows:

1
$short_string=myTruncate($long_string, 100, ' ');

Detecting AJAX Request

Most JavaScript frameworks like jQuery, mootools sends a header HTTP_X_REQUESTED_WITH implementations with Ajax segment, and from which we can verify that the request is sent to the AJAX request no.

1
2
3
4
5
if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    //If AJAX Request Then
}else{
//something else
}

I hope to share in this article will help you a lot in using it on their purpose.

Good luck!

10 PHP code snippets when working with strings (Strings)

10 PHP code snippets when working with strings (Strings) Posted on 03-08-2015  Strings also called chain, is one of the important data type and is used most commonly. The master in handling chain will help a lot for you in the web programming later. In this article, I would like to share 10 string processing code that may use the information you will need in the future. 2.25/10 605

Comment:

To comment you must be logged in members.

Files with category

  • Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    Instructions for installing and configuring Windows Live Mail on Windows 10 simple

    View: 3109    Download: 0   Comment: 0

    Category: References     Fields: Other

    Windows 10 pre-installed Mail application for managing personal email on the device. The latest version of this application but improved a lot and support other email accounts such as Gmail or Yahoo Mail but users almost no "salty" really with this...

  • Step by step instructions to create social networking buttons with CSS3

    Step by step instructions to create social networking buttons with CSS3

    View: 2212    Download: 0   Comment: 0

    Category: References     Fields: Other

    CSS3 help web designers have the ability to create buttons (buttons) very nice, today I will share with you two tips decoration for button in your web becomes radiant beauty that no need to use photoshop.

  • You should understand the CSS Box Shadow

    You should understand the CSS Box Shadow

    View: 2287    Download: 0   Comment: 0

    Category: References     Fields: Other

    Effects his shadow was introduced in the previous article, however, in this article, I will guide more specific about shadow attributes, you try it with anything. First we try to learn css following paragraph:

  • How to do button movement with beautiful CSS3

    How to do button movement with beautiful CSS3

    View: 1986    Download: 0   Comment: 0

    Category: References     Fields: Other

    Previously to create motion effects button, you must draw the button in photoshop, then switched to flash to make it possible to move. But now you need not spend too much time doing it, all because of the emergence of CSS3.

  • Create a dropdown menu with CSS3 effects with beautiful transtions

    Create a dropdown menu with CSS3 effects with beautiful transtions

    View: 2230    Download: 0   Comment: 0

    Category: References     Fields: Other

    More of the dropdown menu you want to introduce to you, this will have the effect menu transitions (converted background of menu background from pale to dark). This menu works well on browsers like FF, Chrome, Safary, but unfortunately did not work...

  • How to hack css for all browsers you should know

    How to hack css for all browsers you should know

    View: 1847    Download: 0   Comment: 0

    Category: References     Fields: Other

    In the process of web design, which makes it the most headaches is how to design web pages that you can run on the browser. Especially when clients use the old as IE6 browser such. However, with this article, you will easily edit interface runs well...

  • Create Accordion with extremely beautiful CSS3

    Create Accordion with extremely beautiful CSS3

    View: 2315    Download: 0   Comment: 0

    Category: References     Fields: Other

    Accordion is a technique that helps you shortened the content that you want displayed on the website. It is often used for the display of submenus. In addition you can also use it for content, images. Before applying this procedure, you have to use...

  • Create the effect Hovercho images with Webkit and CSS3 is great

    Create the effect Hovercho images with Webkit and CSS3 is great

    View: 1978    Download: 0   Comment: 0

    Category: References     Fields: Other

    WebKit is one open source application framework provides the necessary components built one for your web browser. Along with CSS3, cả have contributed to very nice effect những previously only using JavaScript or JQuery thực beige.​

 
File suggestion for you
File top downloads
Codetitle.net - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.net Develope by Vinagon .Ltd