<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>芒果 &#187; 代码</title>
	<atom:link href="http://www.mangguo.org/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mangguo.org</link>
	<description>这里不卖芒果，请另寻他处购买。</description>
	<lastBuildDate>Mon, 06 Sep 2010 00:30:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>10+ 字符串相关的 PHP 代码片段</title>
		<link>http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/</link>
		<comments>http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 00:14:28 +0000</pubDate>
		<dc:creator>芒果</dc:creator>
				<category><![CDATA[代码]]></category>
		<category><![CDATA[CatsWhoCode]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.mangguo.org/?p=4489</guid>
		<description><![CDATA[1、自动移除字符串中的 HTML 标记 在用户表单中，你可能希望移除所有不必要的 HTML 标记。使用 strip_tags() 函数可以简单地做到这一点： $text = strip_tags($input, ""); 来源：http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2 2、获取 $start 和 $end 之间的文本 这是一种每个网站开发人员应该收纳在开发工具箱的功能：给定一个字符串，一个起始位置，一个结束为止，并返回包含在 $start 和 $end 两者之间的文本。 function GetBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]); return $r[0]; } return ''; } 来源：http://www.jonasjohn.de/snippets/php/get-between.htm 3、将 URL 转换为超链接 如果你在 WordPress 博客的评论表单中添加了 URL，它会被自动转换为超级链接。如果你想要在网站上实现同样的功能，可以使用以下代码： $url = "芒果 (http://www.mangguo.org)"; $url = [...]]]></description>
			<content:encoded><![CDATA[<p><strong>1、自动移除字符串中的 HTML 标记</strong></p>
<p>在用户表单中，你可能希望移除所有不必要的 <a href="http://www.mangguo.org/tag/html/">HTML</a> 标记。使用 strip_tags() 函数可以简单地做到这一点：</p>
<pre>$text = strip_tags($input, "");</pre>
<p><strong>来源：<a href="http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2" target="_blank">http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2</a></strong></p>
<p><strong>2、获取 $start 和 $end 之间的文本</strong></p>
<p>这是一种每个网站开发人员应该收纳在开发工具箱的功能：给定一个字符串，一个起始位置，一个结束为止，并返回包含在 $start 和 $end 两者之间的文本。</p>
<pre>function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}</pre>
<p><strong>来源：<a href="http://www.jonasjohn.de/snippets/php/get-between.htm" target="_blank">http://www.jonasjohn.de/snippets/php/get-between.htm</a></strong></p>
<p><strong>3、将 URL 转换为超链接</strong></p>
<p>如果你在 <a href="http://www.mangguo.org/tag/wordpress/">WordPress</a> 博客的评论表单中添加了 URL，它会被自动转换为超级链接。如果你想要在网站上实现同样的功能，可以使用以下代码：</p>
<pre>$url = "芒果 (http://www.mangguo.org)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '<a href="http://www.mangguo.org/$1" target="_blank">$0</a>', $url);</pre>
<p><strong>来源：<a href="http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2" target="_blank">http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2</a></strong></p>
<p><strong>4、将文本分割为 140 字符的数组</strong></p>
<p>大家都知道，<a href="http://twitter.com/mangguo" target="_blank">Twitter</a> 仅仅接受 140 字符以内的消息。如果你希望与这个流行的即时信息网站交互，肯定会喜欢这个功能，这将允许对留言截断为 140 个字符。</p>
<pre>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 . ' ') &lt;= $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;
}</pre>
<p><strong>来源：<a href="http://snipplr.com/view.php?codeview&amp;id=31648" target="_blank">http://snipplr.com/view.php?codeview&amp;id=31648</a></strong></p>
<p><strong>5、从字符串中移除 URL</strong></p>
<p>为了获得流量或者反向链接，很多访客会发布大量含有网址信息的博客评论，这个代码片段可以对其进行有效防范：</p>
<pre>$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&amp;@#\/%?=~_|$!:,.;]*[A-Z0-9+&amp;@#\/%=~_|$]/i', '', $string);</pre>
<p><strong>来源：<a href="http://snipplr.com/view.php?codeview&amp;id=15236" target="_blank">http://snipplr.com/view.php?codeview&amp;id=15236</a></strong></p>
<p><strong>6、转换字符串为缩略标题</strong></p>
<p>创建缩略标题（通常称之为 <a href="http://www.mangguo.org/tag/permalink/">permalink</a>，即固定链接）有利于 <a href="http://www.mangguo.org/tag/seo/">SEO</a>，以下函数以一个字符串作为参数，并返回良好的缩略字符串。简洁有效，值得尝试！</p>
<pre>function slug($str){
	$str = strtolower(trim($str));
	$str = preg_replace('/[^a-z0-9-]/', '-', $str);
	$str = preg_replace('/-+/', "-", $str);
	return $str;
}</pre>
<p><strong>来源：<a href="http://snipplr.com/view.php?codeview&amp;id=2809" target="_blank">http://snipplr.com/view.php?codeview&amp;id=2809</a></strong></p>
<p><strong>7、解析 CSV 文件</strong></p>
<p>CSV（逗号分隔的值文件）是存储数据的简单方式，使用 PHP 解析也很容易。不信你可以动手试试以下代码片段。</p>
<pre>$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";
}</pre>
<p><strong>来源：<a href="http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1" target="_blank">http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1</a></strong></p>
<p><strong>8、检索字符串中的另一个字符串</strong></p>
<p>如果某个字符串包含在另一个字符串中，并且必须检索出来，这里有一个绝妙的方法：</p>
<pre>function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}</pre>
<p><strong>来源：<a href="http://www.jonasjohn.de/snippets/php/contains.htm" target="_blank">http://www.jonasjohn.de/snippets/php/contains.htm</a></strong></p>
<p><strong>9、检测某个字符串是否以指定的模式开始</strong></p>
<p>有些语言比如 Java 具有一个 startWith 方法，允许你检测某个字符串是否以指定的模式开始。不幸的是，<a href="http://www.mangguo.org/tag/php/">PHP</a> 不具备这种内建函数。但我们可以自己动手丰衣足食，实现也很简单：</p>
<pre>function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);
}</pre>
<p><strong>来源：<a href="http://snipplr.com/view.php?codeview&amp;id=2143" target="_blank">http://snipplr.com/view.php?codeview&amp;id=2143</a></strong></p>
<p><strong>10、从字符串中提取电子邮件地址</strong></p>
<p>有没有想过那些发垃圾邮件的人是如何得到邮件地址的？这很简单，他们只需对网页进行简单的 <a href="../tag/html/">HTML</a> 解析即可提取电子邮件。此代码需要一个字符串作为参数，并打印所包含的电子邮件地址。<a href="http://www.mangguo.org/">芒果</a>告诫：请勿使用此代码制造垃圾邮件！</p>
<pre>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;
        &lt;a href="test3@example.org"&gt;foobar&lt;/a&gt;
        &lt;test4@example.org&gt;

        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));</pre>
<p><strong>来源：<a href="http://www.jonasjohn.de/snippets/php/extract-emails.htm" target="_blank">http://www.jonasjohn.de/snippets/php/extract-emails.htm</a></strong></p>
<p>英文原稿：<a href="http://www.catswhocode.com/blog/10-php-code-snippets-for-working-with-strings" target="_blank">10 PHP code snippets for working with strings |  CatsWhoCode</a><br />
翻译整理：<a href="../10-php-code-snippets-for-working-with-strings" target="_blank">10+ 字符串相关的 PHP 代码片段 | 芒果</a></p>
<h3  class="related_post_title">推荐阅读</h3><ul class="related_post"><li><a href="http://www.mangguo.org/10-sites-developers-should-have-in-their-bookmarks/" title="值得网站开发人员收藏的 10 个网站">值得网站开发人员收藏的 10 个网站</a> (5)</li><li><a href="http://www.mangguo.org/manipulating-the-dom-with-jquery-10-useful-code-snippets/" title="使用 jQuery 操作 DOM：10+ 有用的代码片段">使用 jQuery 操作 DOM：10+ 有用的代码片段</a> (3)</li><li><a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/" title="9 个必须知道的实用 PHP 函数和功能">9 个必须知道的实用 PHP 函数和功能</a> (5)</li><li><a href="http://www.mangguo.org/php-unicode-signature-bom-problem/" title="PHP 中的 Unicode 签名 (BOM) 问题">PHP 中的 Unicode 签名 (BOM) 问题</a> (0)</li><li><a href="http://www.mangguo.org/21-useful-handy-php-code-snippet/" title="21+ 实用便捷的 PHP 代码摘录">21+ 实用便捷的 PHP 代码摘录</a> (6)</li><li><a href="http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/" title="超强在线压缩/解压缩 PHP 脚本">超强在线压缩/解压缩 PHP 脚本</a> (3)</li><li><a href="http://www.mangguo.org/9-php-library-developer-should-know/" title="9 个开发人员应该知道的 PHP 库">9 个开发人员应该知道的 PHP 库</a> (2)</li><li><a href="http://www.mangguo.org/15-site-web-developer-and-designer-should-know/" title="Web 设计与开发者必须知道的 15 个站点">Web 设计与开发者必须知道的 15 个站点</a> (6)</li></ul><hr/>
© 2010 <a href="http://www.mangguo.org">芒果</a> 版权所有 |
<a href="http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/">固定链接</a> |
<a href="http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/#comments">4 条评论</a> |
标签 <a href="http://www.mangguo.org/tag/catswhocode/" rel="tag">CatsWhoCode</a>, <a href="http://www.mangguo.org/tag/php/" rel="tag">PHP</a>]]></content:encoded>
			<wfw:commentRss>http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>9 个必须知道的实用 PHP 函数和功能</title>
		<link>http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/</link>
		<comments>http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/#comments</comments>
		<pubDate>Mon, 03 May 2010 05:17:08 +0000</pubDate>
		<dc:creator>芒果</dc:creator>
				<category><![CDATA[代码]]></category>
		<category><![CDATA[Nettuts]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.mangguo.org/?p=3432</guid>
		<description><![CDATA[即使使用 PHP 多年，也会偶然发现一些未曾了解的函数和功能。其中有些是非常有用的，但没有得到充分利用。并不是所有人都会从头到尾一页一页地阅读手册和函数参考！ 1、任意参数数目的函数 你可能已经知道，PHP 允许定义可选参数的函数。但也有完全允许任意数目的函数参数的方法。以下是可选参数的例子： // function with 2 optional arguments function foo($arg1 = '', $arg2 = '') { echo "arg1: $arg1\n"; echo "arg2: $arg2\n"; } foo('hello','world'); /* prints: arg1: hello arg2: world */ foo(); /* prints: arg1: arg2: */ 现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用 func_get_args() 函数： // yes, the argument list can be empty function foo() { [...]]]></description>
			<content:encoded><![CDATA[<p>即使使用 PHP 多年，也会偶然发现一些未曾了解的函数和功能。其中有些是非常有用的，但没有得到充分利用。并不是所有人都会从头到尾一页一页地阅读手册和函数参考！</p>
<p><strong>1、任意参数数目的函数</strong></p>
<p>你可能已经知道，PHP 允许定义可选参数的函数。但也有完全允许任意数目的函数参数的方法。以下是可选参数的例子：</p>
<pre>// function with 2 optional arguments
function foo($arg1 = '', $arg2 = '') {

	echo "arg1: $arg1\n";
	echo "arg2: $arg2\n";

}

foo('hello','world');
/* prints:
arg1: hello
arg2: world
*/

foo();
/* prints:
arg1:
arg2:
*/
</pre>
<p>现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用 func_get_args() 函数：</p>
<pre>// yes, the argument list can be empty
function foo() {

	// returns an array of all passed arguments
	$args = func_get_args();

	foreach ($args as $k =&gt; $v) {
		echo "arg".($k+1).": $v\n";
	}

}

foo();
/* prints nothing */

foo('hello');
/* prints
arg1: hello
*/

foo('hello', 'world', 'again');
/* prints
arg1: hello
arg2: world
arg3: again
*/
</pre>
<p><strong>2、使用 Glob() 查找文件</strong></p>
<p>许多 PHP 函数具有长描述性的名称。然而可能会很难说出 glob() 函数能做的事情，除非你已经通过多次使用并熟悉了它。可以把它看作是比 scandir() 函数更强大的版本，可以按照某种模式搜索文件。</p>
<pre>// get all php files
$files = glob('*.php');

print_r($files);
/* output looks like:
Array
(
    [0] =&gt; phptest.php
    [1] =&gt; pi.php
    [2] =&gt; post_output.php
    [3] =&gt; test.php
)
*/
</pre>
<p>你可以像这样获得多个文件：</p>
<pre>// get all php files AND txt files
$files = glob('*.{php,txt}', GLOB_BRACE);

print_r($files);
/* output looks like:
Array
(
    [0] =&gt; phptest.php
    [1] =&gt; pi.php
    [2] =&gt; post_output.php
    [3] =&gt; test.php
    [4] =&gt; log.txt
    [5] =&gt; test.txt
)
*/
</pre>
<p>请注意，这些文件其实是可以返回一个路径，这取决于查询条件：</p>
<pre>$files = glob('../images/a*.jpg');

print_r($files);
/* output looks like:
Array
(
    [0] =&gt; ../images/apple.jpg
    [1] =&gt; ../images/art.jpg
)
*/
</pre>
<p>如果你想获得每个文件的完整路径，你可以调用 realpath() 函数： </p>
<pre>$files = glob('../images/a*.jpg');

// applies the function to each array element
$files = array_map('realpath',$files);

print_r($files);
/* output looks like:
Array
(
    [0] =&gt; C:\wamp\www\images\apple.jpg
    [1] =&gt; C:\wamp\www\images\art.jpg
)
*/
</pre>
<p><strong>3、内存使用信息</strong></p>
<p>通过侦测脚本的内存使用情况，有利于代码的优化。PHP 提供了一个垃圾收集器和一个非常复杂的内存管理器。脚本执行时所使用的内存量，有升有跌。为了得到当前的内存使用情况，我们可以使用 memory_get_usage() 函数。如果需要获得任意时间点的最高内存使用量，则可以使用 memory_limit() 函数。</p>
<pre>echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/

// let's use up some memory
for ($i = 0; $i &lt; 100000; $i++) {
	$array []= md5($i);
}

// let's remove half of the array
for ($i = 0; $i &lt; 100000; $i++) {
	unset($array[$i]);
}

echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/

echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes
*/</pre>
<p><strong>4、CPU 使用信息</strong></p>
<p>为此，我们要利用 getrusage() 函数。请记住这个函数不适用于 Windows 平台。</p>
<pre>print_r(getrusage());
/* prints
Array
(
    [ru_oublock] =&gt; 0
    [ru_inblock] =&gt; 0
    [ru_msgsnd] =&gt; 2
    [ru_msgrcv] =&gt; 3
    [ru_maxrss] =&gt; 12692
    [ru_ixrss] =&gt; 764
    [ru_idrss] =&gt; 3864
    [ru_minflt] =&gt; 94
    [ru_majflt] =&gt; 0
    [ru_nsignals] =&gt; 1
    [ru_nvcsw] =&gt; 67
    [ru_nivcsw] =&gt; 4
    [ru_nswap] =&gt; 0
    [ru_utime.tv_usec] =&gt; 0
    [ru_utime.tv_sec] =&gt; 0
    [ru_stime.tv_usec] =&gt; 6269
    [ru_stime.tv_sec] =&gt; 0
)

*/</pre>
<p>这可能看起来有点神秘，除非你已经有系统管理员权限。以下是每个值的具体说明（你不需要记住这些）：</p>
<pre>ru_oublock: block output operations
ru_inblock: block input operations
ru_msgsnd: messages sent
ru_msgrcv: messages received
ru_maxrss: maximum resident set size
ru_ixrss: integral shared memory size
ru_idrss: integral unshared data size
ru_minflt: page reclaims
ru_majflt: page faults
ru_nsignals: signals received
ru_nvcsw: voluntary context switches
ru_nivcsw: involuntary context switches
ru_nswap: swaps
ru_utime.tv_usec: user time used (microseconds)
ru_utime.tv_sec: user time used (seconds)
ru_stime.tv_usec: system time used (microseconds)
ru_stime.tv_sec: system time used (seconds)</pre>
<p>要知道脚本消耗多少 CPU 功率，我们需要看看 &#8216;user time&#8217; 和 &#8216;system time&#8217; 两个参数的值。秒和微秒部分默认是单独提供的。你可以除以 100 万微秒，并加上秒的参数值，得到一个十进制的总秒数。让我们来看一个例子：</p>
<pre>// sleep for 3 seconds (non-busy)
sleep(3);

$data = getrusage();
echo "User time: ".
	($data['ru_utime.tv_sec'] +
	$data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
	($data['ru_stime.tv_sec'] +
	$data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 0.011552
System time: 0
*/
</pre>
<p>尽管脚本运行用了大约 3 秒钟，CPU 使用率却非常非常低。因为在睡眠运行的过程中，该脚本实际上不消耗 CPU 资源。还有许多其他的任务，可能需要一段时间，但不占用类似等待磁盘操作等 CPU 时间。因此正如你所看到的，CPU 使用率和运行时间的实际长度并不总是相同的。下面是一个例子：</p>
<pre>// loop 10 million times (busy)
for($i=0;$i&lt;10000000;$i++) {

}

$data = getrusage();
echo "User time: ".
	($data['ru_utime.tv_sec'] +
	$data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
	($data['ru_stime.tv_sec'] +
	$data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 1.424592
System time: 0.004204
*/
</pre>
<p>这花了大约 1.4 秒的 CPU 时间，但几乎都是用户时间，因为没有系统调用。系统时间是指花费在执行程序的系统调用时的 CPU 开销。下面是一个例子：</p>
<pre>$start = microtime(true);
// keep calling microtime for about 3 seconds
while(microtime(true) - $start &lt; 3) {

}

$data = getrusage();
echo "User time: ".
	($data['ru_utime.tv_sec'] +
	$data['ru_utime.tv_usec'] / 1000000);
echo "System time: ".
	($data['ru_stime.tv_sec'] +
	$data['ru_stime.tv_usec'] / 1000000);

/* prints
User time: 1.088171
System time: 1.675315
*/
</pre>
<p>现在我们有相当多的系统时间占用。这是因为脚本多次调用 microtime() 函数，该函数需要向操作系统发出请求，以获取所需时间。你也可能会注意到运行时间加起来不到 3 秒。这是因为有可能在服务器上同时存在其他进程，并且脚本没有 100% 使用 CPU 的整个 3 秒持续时间。</p>
<p><strong>5、魔术常量 </strong></p>
<p>PHP 提供了获取当前行号 (__LINE__)、文件路径 (__FILE__)、目录路径 (__DIR__)、函数名 (__FUNCTION__)、类名 (__CLASS__)、方法名 (__METHOD__) 和命名空间 (__NAMESPACE__) 等有用的魔术常量。在这篇文章中不作一一介绍，但是我将告诉你一些用例。当包含其他脚本文件时，使用 __FILE__ 常量（或者使用 PHP5.3 新具有的 __DIR__ 常量）：</p>
<pre>// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
require_once('config/database.php');

// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . '/config/database.php');
</pre>
<p>使用 __LINE__ 使得调试更为轻松。你可以跟踪到具体行号。</p>
<pre>// some code
// ...
my_debug("some debug message", __LINE__);
/* prints
Line 4: some debug message
*/

// some more code
// ...
my_debug("another debug message", __LINE__);
/* prints
Line 11: another debug message
*/

function my_debug($msg, $line) {
	echo "Line $line: $msg\n";
}
</pre>
<p><strong>6、生成唯一标识符</strong></p>
<p>某些场景下，可能需要生成一个唯一的字符串。我看到很多人使用 md5() 函数，即使它并不完全意味着这个目的：</p>
<pre>// generate unique string
echo md5(time() . mt_rand(1,1000000));
</pre>
<p>There is actually a PHP function named uniqid() that is meant to be used for this.</p>
<pre>// generate unique string
echo uniqid();
/* prints
4bd67c947233e
*/

// generate another unique string
echo uniqid();
/* prints
4bd67c9472340
*/
</pre>
<p>你可能会注意到，尽管字符串是唯一的，前几个字符却是类似的，这是因为生成的字符串与服务器时间相关。但实际上也存在友好的一方面，由于每个新生成的 ID 会按字母顺序排列，这样排序就变得很简单。为了减少重复的概率，你可以传递一个前缀，或第二个参数来增加熵：</p>
<pre>// with prefix
echo uniqid('foo_');
/* prints
foo_4bd67d6cd8b8f
*/

// with more entropy
echo uniqid('',true);
/* prints
4bd67d6cd8b926.12135106
*/

// both
echo uniqid('bar_',true);
/* prints
bar_4bd67da367b650.43684647
*/
</pre>
<p>这个函数将产生比 md5() 更短的字符串，能节省一些空间。</p>
<p><strong>7、序列化</strong></p>
<p>你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况？你可能没能想出一个格式化字符串并转换成数组或对象的好方法，PHP 已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子，使用 serialize() 和 unserialize() 函数：</p>
<pre>// a complex array
$myvar = array(
	'hello',
	42,
	array(1,'two'),
	'apple'
);

// convert to a string
$string = serialize($myvar);

echo $string;
/* prints
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
*/

// you can reproduce the original variable
$newvar = unserialize($string);

print_r($newvar);
/* prints
Array
(
    [0] =&gt; hello
    [1] =&gt; 42
    [2] =&gt; Array
        (
            [0] =&gt; 1
            [1] =&gt; two
        )

    [3] =&gt; apple
)
*/</pre>
<p>这是原生的 PHP 序列化方法。然而，由于 JSON 近年来大受欢迎，PHP5.2 中已经加入了对 JSON 格式的支持。现在你可以使用 json_encode() 和 json_decode() 函数：</p>
<pre>// a complex array
$myvar = array(
	'hello',
	42,
	array(1,'two'),
	'apple'
);

// convert to a string
$string = json_encode($myvar);

echo $string;
/* prints
["hello",42,[1,"two"],"apple"]
*/

// you can reproduce the original variable
$newvar = json_decode($string);

print_r($newvar);
/* prints
Array
(
    [0] =&gt; hello
    [1] =&gt; 42
    [2] =&gt; Array
        (
            [0] =&gt; 1
            [1] =&gt; two
        )

    [3] =&gt; apple
)
*/
</pre>
<p>这将更为行之有效，尤其与 JavaScript 等许多其他语言兼容。然而对于复杂的对象，某些信息可能会丢失。</p>
<p><strong>8、压缩字符串</strong></p>
<p>在谈到压缩时，我们通常想到文件压缩，如 ZIP 压缩等。在 PHP 中字符串压缩也是可能的，但不涉及任何压缩文件。在下面的例子中，我们要利用 gzcompress() 和 gzuncompress() 函数：</p>
<pre>$string =
"Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. ";

$compressed = gzcompress($string);

echo "Original size: ". strlen($string)."\n";
/* prints
Original size: 800
*/

echo "Compressed size: ". strlen($compressed)."\n";
/* prints
Compressed size: 418
*/

// getting it back
$original = gzuncompress($compressed);</pre>
<p>这种操作的压缩率能达到 50% 左右。另外的函数 gzencode() 和 gzdecode() 能达到类似结果，通过使用不同的压缩算法。</p>
<p><strong>9、注册停止功能</strong></p>
<p>有一个函数叫做 register_shutdown_function()，可以让你在某段脚本完成运行之前，执行一些指定代码。假设你需要在脚本执行结束前捕获一些基准统计信息，例如运行的时间长度：</p>
<pre>// capture the start time
$start_time = microtime(true);

// do some stuff
// ...

// display how long the script took
echo "execution took: ".
		(microtime(true) - $start_time).
		" seconds.";
</pre>
<p>这似乎微不足道，你只需要在脚本运行的最后添加相关代码。但是如果你调用过 exit() 函数，该代码将无法运行。此外，如果有一个致命的错误，或者脚本被用户意外终止，它可能无法再次运行。当你使用 register_shutdown_function() 函数，代码将继续执行，不论脚本是否停止运行：</p>
<pre>$start_time = microtime(true);

register_shutdown_function('my_shutdown');

// do some stuff
// ...

function my_shutdown() {
	global $start_time;

	echo "execution took: ".
			(microtime(true) - $start_time).
			" seconds.";
}</pre>
<p>英文原稿：<a href="http://net.tutsplus.com/tutorials/php/9-useful-php-functions-and-features-you-need-to-know/" target="_blank">9 Useful PHP Functions and Features You Need to Know | Nettuts</a><br />
翻译整理：<a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know" target="_blank">9 个必须知道的实用 PHP 函数和功能 | 芒果</a></p>
<h3  class="related_post_title">推荐阅读</h3><ul class="related_post"><li><a href="http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/" title="10+ 字符串相关的 PHP 代码片段">10+ 字符串相关的 PHP 代码片段</a> (4)</li><li><a href="http://www.mangguo.org/pure-css-text-gradients-effect/" title="纯 CSS 实现文本渐变效果">纯 CSS 实现文本渐变效果</a> (6)</li><li><a href="http://www.mangguo.org/php-unicode-signature-bom-problem/" title="PHP 中的 Unicode 签名 (BOM) 问题">PHP 中的 Unicode 签名 (BOM) 问题</a> (0)</li><li><a href="http://www.mangguo.org/8-features-to-look-forward-to-in-wordpress-3-0/" title="WordPress 3.0 值得期待的 8 个特性">WordPress 3.0 值得期待的 8 个特性</a> (5)</li><li><a href="http://www.mangguo.org/quick-tip-html-5-video-with-a-fallback-to-flash/" title="快速技巧：可退回到 Flash 的 HTML5 视频方案 ">快速技巧：可退回到 Flash 的 HTML5 视频方案 </a> (0)</li><li><a href="http://www.mangguo.org/21-useful-handy-php-code-snippet/" title="21+ 实用便捷的 PHP 代码摘录">21+ 实用便捷的 PHP 代码摘录</a> (6)</li><li><a href="http://www.mangguo.org/25-useful-web-design-development-blog/" title="25+ 最有用的网页设计开发类博客">25+ 最有用的网页设计开发类博客</a> (4)</li><li><a href="http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/" title="超强在线压缩/解压缩 PHP 脚本">超强在线压缩/解压缩 PHP 脚本</a> (3)</li></ul><hr/>
© 2010 <a href="http://www.mangguo.org">芒果</a> 版权所有 |
<a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/">固定链接</a> |
<a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/#comments">5 条评论</a> |
标签 <a href="http://www.mangguo.org/tag/nettuts/" rel="tag">Nettuts</a>, <a href="http://www.mangguo.org/tag/php/" rel="tag">PHP</a>]]></content:encoded>
			<wfw:commentRss>http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>21+ 实用便捷的 PHP 代码摘录</title>
		<link>http://www.mangguo.org/21-useful-handy-php-code-snippet/</link>
		<comments>http://www.mangguo.org/21-useful-handy-php-code-snippet/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 14:57:18 +0000</pubDate>
		<dc:creator>芒果</dc:creator>
				<category><![CDATA[代码]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Developer Plus]]></category>

		<guid isPermaLink="false">http://www.mangguo.org/?p=2837</guid>
		<description><![CDATA[PHP 是目前使用最广泛的基于 Web 的编程语言，驱动着数以百万计的网站，其中也包括如 Facebook 等一些大型站点。这里收集了 21 段实用便捷的 PHP 代码摘录，对每种类型的 PHP 开发者都会有所帮助。 1. 可阅读随机字符串 此代码将创建一个可阅读的字符串，使其更接近词典中的单词，实用且具有密码验证功能。 /************** *@length - length of random string (must be a multiple of 2) **************/ function readable_random_string($length = 6){ $conso=array("b","c","d","f","g","h","j","k","l", "m","n","p","r","s","t","v","w","x","y","z"); $vocal=array("a","e","i","o","u"); $password=""; srand ((double)microtime()*1000000); $max = $length/2; for($i=1; $i&#60;=$max; $i++) { $password.=$conso[rand(0,19)]; $password.=$vocal[rand(0,4)]; } return $password; } 2. 生成一个随机字符串 如果不需要可阅读的字符串，使用此函数替代，即可创建一个随机字符串，作为用户的随机密码等。 [...]]]></description>
			<content:encoded><![CDATA[<p>PHP 是目前使用最广泛的基于 Web 的编程语言，驱动着数以百万计的网站，其中也包括如 Facebook 等一些大型站点。这里收集了 21 段实用便捷的 PHP 代码摘录，对每种类型的 PHP 开发者都会有所帮助。</p>
<p><strong>1. 可阅读随机字符串</strong></p>
<p>此代码将创建一个可阅读的字符串，使其更接近词典中的单词，实用且具有密码验证功能。</p>
<pre>/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
    $conso=array("b","c","d","f","g","h","j","k","l",
    "m","n","p","r","s","t","v","w","x","y","z");
    $vocal=array("a","e","i","o","u");
    $password="";
    srand ((double)microtime()*1000000);
    $max = $length/2;
    for($i=1; $i&lt;=$max; $i++)
    {
    $password.=$conso[rand(0,19)];
    $password.=$vocal[rand(0,4)];
    }
    return $password;
}</pre>
<p><strong>2. 生成一个随机字符串</strong></p>
<p>如果不需要可阅读的字符串，使用此函数替代，即可创建一个随机字符串，作为用户的随机密码等。</p>
<pre>/*************
*@l - length of random string
*/
function generate_rand($l){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  srand((double)microtime()*1000000);
  for($i=0; $i&lt;$l; $i++) {
      $rand.= $c[rand()%strlen($c)];
  }
  return $rand;
 }</pre>
<p><strong>3. 编码电子邮件地址</strong></p>
<p>使用此代码，可以将任何电子邮件地址编码为 HTML 字符实体，以防止被垃圾邮件程序收集。</p>
<pre>function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
{
    // remplazar aroba y puntos
    $email = str_replace('@', '&amp;#64;', $email);
    $email = str_replace('.', '&amp;#46;', $email);
    $email = str_split($email, 5);  

    $linkText = str_replace('@', '&amp;#64;', $linkText);
    $linkText = str_replace('.', '&amp;#46;', $linkText);
    $linkText = str_split($linkText, 5);  

    $part1 = '&lt;a href="ma';
    $part2 = 'ilto&amp;#58;';
    $part3 = '" '. $attrs .' &gt;';
    $part4 = '&lt;/a&gt;';  

    $encoded = '&lt;script type="text/javascript"&gt;';
    $encoded .= "document.write('$part1');";
    $encoded .= "document.write('$part2');";
    foreach($email as $e)
    {
            $encoded .= "document.write('$e');";
    }
    $encoded .= "document.write('$part3');";
    foreach($linkText as $l)
    {
            $encoded .= "document.write('$l');";
    }
    $encoded .= "document.write('$part4');";
    $encoded .= '&lt;/script&gt;';  

    return $encoded;
}</pre>
<p><strong>4. 验证邮件地址</strong></p>
<p>电子邮件验证也许是中最常用的网页表单验证，此代码除了验证电子邮件地址，也可以选择检查邮件域所属 DNS 中的 MX 记录，使邮件验证功能更加强大。</p>
<pre>function is_valid_email($email, $test_mx = false)
{
    if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
        if($test_mx)
        {
            list($username, $domain) = split("@", $email);
            return getmxrr($domain, $mxrecords);
        }
        else
            return true;
    else
        return false;
}</pre>
<p><strong>5. 列出目录内容</strong></p>
<pre>function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." &amp;&amp; $file != ".." &amp;&amp; $file != "Thumbs.db")
                {
                    echo '&lt;a target="_blank" href="'.$dir.$file.'"&gt;'.$file.'&lt;/a&gt;&lt;br&gt;'."\n";
                }
            }
            closedir($handle);
        }
    }
}</pre>
<p><strong>6. 销毁目录</strong></p>
<p>删除一个目录，包括它的内容。</p>
<pre>/*****
*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
*/
function destroyDir($dir, $virtual = false)
{
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) &amp;&amp; $handle = opendir($dir))
    {
        while ($file = readdir($handle))
        {
            if ($file == '.' || $file == '..')
            {
                continue;
            }
            elseif (is_dir($dir.$ds.$file))
            {
                destroyDir($dir.$ds.$file);
            }
            else
            {
                unlink($dir.$ds.$file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    }
    else
    {
        return false;
    }
}</pre>
<p><strong>7. 解析 JSON 数据</strong></p>
<p>与大多数流行的 Web 服务如 Twitter 通过开放 API 来提供数据一样，它总是能够知道如何解析 API 数据的各种传送格式，包括 JSON，XML 等等。</p>
<pre>$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj-&gt;name; //prints foo
echo $obj-&gt;interest[1]; //prints php</pre>
<p><strong>8. 解析 XML 数据</strong></p>
<pre>//xml string
$xml_string="&lt;?xml version='1.0'?&gt;
&lt;users&gt;
   &lt;user id='398'&gt;
      &lt;name&gt;Foo&lt;/name&gt;
      &lt;email&gt;foo@bar.com&lt;/name&gt;
   &lt;/user&gt;
   &lt;user id='867'&gt;
      &lt;name&gt;Foobar&lt;/name&gt;
      &lt;email&gt;foobar@foo.com&lt;/name&gt;
   &lt;/user&gt;
&lt;/users&gt;";  

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);  

//loop through the each node of user
foreach ($xml-&gt;user as $user)
{
   //access attribute
   echo $user['id'], '  ';
   //subnodes are accessed by -&gt; operator
   echo $user-&gt;name, '  ';
   echo $user-&gt;email, '&lt;br /&gt;';
}</pre>
<p><strong>9. 创建日志缩略名</strong></p>
<p>创建用户友好的日志缩略名。</p>
<pre>function create_slug($string){
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
    return $slug;
}</pre>
<p><strong>10. 获取客户端真实 IP 地址</strong></p>
<p>该函数将获取用户的真实 IP 地址，即便他使用代理服务器。</p>
<pre>function getRealIpAddr()
{
    if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
    //to check ip is pass from proxy
    {
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}</pre>
<p><strong>11. 强制性文件下载</strong></p>
<p>为用户提供强制性的文件下载功能。</p>
<pre>/********************
*@file - path to file
*/
function force_download($file)
{
    if ((isset($file))&amp;&amp;(file_exists($file))) {
       header("Content-length: ".filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
       readfile("$file");
    } else {
       echo "No file selected";
    }
}</pre>
<p><strong>12. 创建标签云</strong></p>
<pre>function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
{
    $minimumCount = min( array_values( $data ) );
    $maximumCount = max( array_values( $data ) );
    $spread       = $maximumCount - $minimumCount;
    $cloudHTML    = '';
    $cloudTags    = array();  

    $spread == 0 &amp;&amp; $spread = 1;  

    foreach( $data as $tag =&gt; $count )
    {
        $size = $minFontSize + ( $count - $minimumCount )
            * ( $maxFontSize - $minFontSize ) / $spread;
        $cloudTags[] = '&lt;a style="font-size: ' . floor( $size ) . 'px'
        . '" href="#" title="\'' . $tag  .
        '\' returned a count of ' . $count . '"&gt;'
        . htmlspecialchars( stripslashes( $tag ) ) . '&lt;/a&gt;';
    }  

    return join( "\n", $cloudTags ) . "\n";
}
/**************************
****   Sample usage    ***/
$arr = Array('Actionscript' =&gt; 35, 'Adobe' =&gt; 22, 'Array' =&gt; 44, 'Background' =&gt; 43,
    'Blur' =&gt; 18, 'Canvas' =&gt; 33, 'Class' =&gt; 15, 'Color Palette' =&gt; 11, 'Crop' =&gt; 42,
    'Delimiter' =&gt; 13, 'Depth' =&gt; 34, 'Design' =&gt; 8, 'Encode' =&gt; 12, 'Encryption' =&gt; 30,
    'Extract' =&gt; 28, 'Filters' =&gt; 42);
echo getCloud($arr, 12, 36);</pre>
<p><strong>13. 寻找两个字符串的相似性</strong></p>
<p>PHP 提供了一个极少使用的 similar_text 函数，但此函数非常有用，用于比较两个字符串并返回相似程度的百分比。</p>
<pre>similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity</pre>
<p><strong>14. 在应用程序中使用 Gravatar 通用头像</strong></p>
<p>随着 WordPress 越来越普及，Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API，将其纳入应用程序也变得十分方便。</p>
<pre>/******************
*@email - Email address to show gravatar for
*@size - size of gravatar
*@default - URL of default gravatar to use
*@rating - rating of Gravatar(G, PG, R, X)
*/
function show_gravatar($email, $size, $default, $rating)
{
    echo '&lt;img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).
        '&amp;default='.$default.'&amp;size='.$size.'&amp;rating='.$rating.'" width="'.$size.'px"
        height="'.$size.'px" /&gt;';
}</pre>
<p><strong>15. 在字符断点处截断文字</strong></p>
<p>所谓断字 (word break)，即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。</p>
<pre>// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=".", $pad="...") {
    // return with no change if string is shorter than $limit
    if(strlen($string) &lt;= $limit)
        return $string;   

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {
        if($breakpoint &lt; strlen($string) - 1) {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }
    return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string, 100, ' ');</pre>
<p><strong>16. 文件 Zip 压缩</strong></p>
<pre>/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) &amp;&amp; !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip-&gt;open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip-&gt;addFile($file,$file);
        }
        //debug
        //echo 'The zip archive contains ',$zip-&gt;numFiles,' files with a status of ',$zip-&gt;status;  

        //close the zip -- done!
        $zip-&gt;close();  

        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);</pre>
<p><strong>17. 解压缩 Zip 文件</strong></p>
<pre>/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip-&gt;open($file) !== TRUE) {
        die (’Could not open archive’);
    }
    // extract contents to destination directory
    $zip-&gt;extractTo($destination);
    // close archive
    $zip-&gt;close();
    echo 'Archive extracted to directory';
}</pre>
<p><strong>18. 为 URL 地址预设 http 字符串</strong></p>
<p>有时需要接受一些表单中的网址输入，但用户很少添加 http:// 字段，此代码将为网址添加该字段。</p>
<pre>if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
   $_POST['url'] = 'http://'.$_POST['url'];
}</pre>
<p><strong>19. 将网址字符串转换成超级链接</strong></p>
<p>该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。</p>
<pre>function makeClickableLinks($text) {
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&amp;//=]+)',
 '&lt;a href="\1"&gt;\1&lt;/a&gt;', $text);
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&amp;//=]+)',
 '\1&lt;a href="http://\2"&gt;\2&lt;/a&gt;', $text);
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
 '&lt;a href="mailto:\1"&gt;\1&lt;/a&gt;', $text);  

return $text;
}</pre>
<p><strong>20. 调整图像尺寸</strong></p>
<p>创建图像缩略图需要许多时间，此代码将有助于了解缩略图的逻辑。</p>
<pre>/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
    $ext = explode(".", $filename);
    $ext = $ext[count($ext)-1];  

    if($ext == "jpg" || $ext == "jpeg")
        $im = imagecreatefromjpeg($tmpname);
    elseif($ext == "png")
        $im = imagecreatefrompng($tmpname);
    elseif($ext == "gif")
        $im = imagecreatefromgif($tmpname);  

    $x = imagesx($im);
    $y = imagesy($im);  

    if($x &lt;= $xmax &amp;&amp; $y &lt;= $ymax)
        return $im;  

    if($x &gt;= $y) {
        $newx = $xmax;
        $newy = $newx * $y / $x;
    }
    else {
        $newy = $ymax;
        $newx = $x / $y * $newy;
    }  

    $im2 = imagecreatetruecolor($newx, $newy);
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    return $im2;
}</pre>
<p><strong>21. 检测 Ajax 请求</strong></p>
<p>大多数的 JavaScript 框架如 jQuery，Mootools 等，在发出 Ajax 请求时，都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息，头当他们一个ajax请求，因此你可以在服务器端侦测到 Ajax 请求。</p>
<pre>if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    //If AJAX Request Then
}else{
//something else
}</pre>
<p>英文原稿：<a href="http://webdeveloperplus.com/php/21-really-useful-handy-php-code-snippets/" target="_blank">21 Really Useful &amp; Handy PHP Code Snippets | Web Developer Plus</a><br />
翻译整理：<a href="http://www.mangguo.org/21-useful-handy-php-code-snippet" target="_blank">21+ 实用便捷的 PHP 代码摘录 | 芒果</a></p>
<h3  class="related_post_title">推荐阅读</h3><ul class="related_post"><li><a href="http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/" title="10+ 字符串相关的 PHP 代码片段">10+ 字符串相关的 PHP 代码片段</a> (4)</li><li><a href="http://www.mangguo.org/40-fresh-beautiful-examples-of-websites-with-large-backgrounds/" title="40+ 新鲜漂亮的大背景网站设计">40+ 新鲜漂亮的大背景网站设计</a> (0)</li><li><a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/" title="9 个必须知道的实用 PHP 函数和功能">9 个必须知道的实用 PHP 函数和功能</a> (5)</li><li><a href="http://www.mangguo.org/php-unicode-signature-bom-problem/" title="PHP 中的 Unicode 签名 (BOM) 问题">PHP 中的 Unicode 签名 (BOM) 问题</a> (0)</li><li><a href="http://www.mangguo.org/30-fresh-amazing-jquery-plugin-and-tutorial/" title="30+ 新鲜惊奇的 jQuery 插件与教程">30+ 新鲜惊奇的 jQuery 插件与教程</a> (5)</li><li><a href="http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/" title="超强在线压缩/解压缩 PHP 脚本">超强在线压缩/解压缩 PHP 脚本</a> (3)</li><li><a href="http://www.mangguo.org/9-php-library-developer-should-know/" title="9 个开发人员应该知道的 PHP 库">9 个开发人员应该知道的 PHP 库</a> (2)</li><li><a href="http://www.mangguo.org/21-amazing-css-technique/" title="21 个令人惊叹的 CSS 技巧">21 个令人惊叹的 CSS 技巧</a> (5)</li></ul><hr/>
© 2010 <a href="http://www.mangguo.org">芒果</a> 版权所有 |
<a href="http://www.mangguo.org/21-useful-handy-php-code-snippet/">固定链接</a> |
<a href="http://www.mangguo.org/21-useful-handy-php-code-snippet/#comments">6 条评论</a> |
标签 <a href="http://www.mangguo.org/tag/php/" rel="tag">PHP</a>, <a href="http://www.mangguo.org/tag/web-developer-plus/" rel="tag">Web Developer Plus</a>]]></content:encoded>
			<wfw:commentRss>http://www.mangguo.org/21-useful-handy-php-code-snippet/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>超强在线压缩/解压缩 PHP 脚本</title>
		<link>http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/</link>
		<comments>http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/#comments</comments>
		<pubDate>Fri, 04 Dec 2009 02:25:57 +0000</pubDate>
		<dc:creator>芒果</dc:creator>
				<category><![CDATA[代码]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.mangguo.org/?p=2777</guid>
		<description><![CDATA[使用虚拟主机，一般仅有 FTP 上传和简单的后台管理功能。如果网络环境不顺畅，FTP 的传输速度会无法让人忍受。 某些主机供应商，如芒果使用的梦游 (MEyu.net) 主机，提供了在线解压缩功能，大大节省了文件传送时间。如果没有这功能，只要主机支持 PHP 环境，不妨利用该脚本代码执行在线解压缩。 该压缩包附带压缩 (zip.php) 和 解压缩 (unzip.php) 两个程序。 使用方法： 在线压缩：选定要压缩的文件或目录（包含子目录），即可开始压缩。压缩的结果保留原来的目录结构。 在线解压：把 zip 文件通过 FTP 上传到本文件相同的目录下，选择 zip 文件；或直接点击“浏览&#8230;”上传 zip 文件。解压的结果保留原来的目录结构。 下载地址：http://www.mangguo.org/wp-content/uploads/2009/12/zip.rar 推荐阅读10+ 字符串相关的 PHP 代码片段 (4)9 个必须知道的实用 PHP 函数和功能 (5)PHP 中的 Unicode 签名 (BOM) 问题 (0)21+ 实用便捷的 PHP 代码摘录 (6)9 个开发人员应该知道的 PHP 库 (2)ZendCore，Apache+MySQL+PHP 环境套件 (5)PHP 根据 IP 地址控制访问 [...]]]></description>
			<content:encoded><![CDATA[<p>使用虚拟主机，一般仅有 FTP 上传和简单的后台管理功能。如果网络环境不顺畅，FTP 的传输速度会无法让人忍受。</p>
<p>某些主机供应商，如芒果使用的<a href="http://www.meyu.org.cn/" target="_blank">梦游 (MEyu.net) 主机</a>，提供了在线解压缩功能，大大节省了文件传送时间。如果没有这功能，只要主机支持 PHP 环境，不妨利用该脚本代码执行在线解压缩。</p>
<p>该压缩包附带压缩 (zip.php) 和 解压缩 (unzip.php) 两个程序。</p>
<p>使用方法：</p>
<p><strong>在线压缩：</strong>选定要压缩的文件或目录（包含子目录），即可开始压缩。压缩的结果保留原来的目录结构。</p>
<p><strong>在线解压：</strong>把 zip 文件通过 FTP 上传到本文件相同的目录下，选择 zip 文件；或直接点击“浏览&#8230;”上传 zip 文件。解压的结果保留原来的目录结构。</p>
<p><strong>下载地址：</strong><a href="http://www.mangguo.org/wp-content/uploads/2009/12/zip.rar" target="_blank">http://www.mangguo.org/wp-content/uploads/2009/12/zip.rar</a></p>
<h3  class="related_post_title">推荐阅读</h3><ul class="related_post"><li><a href="http://www.mangguo.org/10-php-code-snippets-for-working-with-strings/" title="10+ 字符串相关的 PHP 代码片段">10+ 字符串相关的 PHP 代码片段</a> (4)</li><li><a href="http://www.mangguo.org/9-useful-php-functions-and-features-you-need-to-know/" title="9 个必须知道的实用 PHP 函数和功能">9 个必须知道的实用 PHP 函数和功能</a> (5)</li><li><a href="http://www.mangguo.org/php-unicode-signature-bom-problem/" title="PHP 中的 Unicode 签名 (BOM) 问题">PHP 中的 Unicode 签名 (BOM) 问题</a> (0)</li><li><a href="http://www.mangguo.org/21-useful-handy-php-code-snippet/" title="21+ 实用便捷的 PHP 代码摘录">21+ 实用便捷的 PHP 代码摘录</a> (6)</li><li><a href="http://www.mangguo.org/9-php-library-developer-should-know/" title="9 个开发人员应该知道的 PHP 库">9 个开发人员应该知道的 PHP 库</a> (2)</li><li><a href="http://www.mangguo.org/zendcore-apache-mysql-php-environment-package/" title="ZendCore，Apache+MySQL+PHP 环境套件">ZendCore，Apache+MySQL+PHP 环境套件</a> (5)</li><li><a href="http://www.mangguo.org/php-access-control-according-to-ip-address/" title="PHP 根据 IP 地址控制访问">PHP 根据 IP 地址控制访问</a> (6)</li></ul><hr/>
© 2009 <a href="http://www.mangguo.org">芒果</a> 版权所有 |
<a href="http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/">固定链接</a> |
<a href="http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/#comments">3 条评论</a> |
标签 <a href="http://www.mangguo.org/tag/php/" rel="tag">PHP</a>]]></content:encoded>
			<wfw:commentRss>http://www.mangguo.org/super-powerful-online-zip-unzip-php-script/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
