10个用于操作字符串的 PHP代码片段

0
PHP Perl C/C++ Go 14552 次浏览
字符串是一种非常重要的数据类型,是我们在日常Web开发工作中常用需要处理的任务。在这篇文章中,将为大家介绍10个非常实用的函数和代码片段,可以让你的开发工作变得更加轻松。

Automatically remove html tags from a string(删除字符串的html标签)

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(删除字符串中URL地址

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(解析CVS文件)

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

        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

请尽量让自己的答案能够对别人有帮助

10个答案

默认排序 按投票排序