本文实例总结了php中非常有用却鲜有人知的函数。分享给大家供大家参考,具体如下:

php里有非常丰富的内置函数,很多我们都用过,但仍有很多的函数我们大部分人都不熟悉,可它们却十分的有用。这篇文章里,我列举了一些鲜为人知但会让你眼睛一亮的php函数。

levenshtein()

你有没有经历过需要知道两个单词有多大的不同的时候,这个函数就是来帮你解决这个问题的。它能比较出两个字符串的不同程度。

用法:

$str1 = "carrot";
$str2 = "carrrott";
echo levenshtein($str1, $str2); //outputs 2

get_defined_vars()

这是一个在debug调试时非常有用的函数。这个函数返回一个多维数组,里面包含了所有定义过的变量。

用法:

print_r(get_defined_vars());

php_check_syntax()

这个函数非常的有用,可以用来检查php的语法是否正确。出于技术上的原因,从php 5.05开始,这个函数被删除了。

用法:

$error_message = "";
$filename = "./php_script.php";
if(!php_check_syntax($filename, &$error_message)) {
echo "errors were found in the file $filename: $error_message";
} else {
echo "the file $filename contained no syntax errors";

ignore_user_abort()

这个函数用来拒绝浏览器端用户终止执行脚本的请求。正常情况下客户端的退出会导致服务器端脚本停止运行。

用法:

ignore_user_abort();

highlight_string()

当你想把php代码显示到页面上时,highlight_string()函数就会显得非常有用。这个函数会把你提供的php代码用内置的php语法突出显示定义的颜色高亮显示。这个函数有两个参数,第一个参数是一个字符串,表示这个字符串需要被突出显示。第二个参数如果设置成true,这个函数就会把高亮后的代码当成返回值返回。

用法:

highlight_string('<?php phpinfo(); ?>');

highlight_file

这是一个非常有用的php函数,它能返回指定的php文件,并按照语法语义用高亮颜色突出显示文件内容。其中的突出显示的代码都是用html标记处理过的。

用法:

highlight_file("php_script.php");

php_strip_whitespace

这个函数也跟前面的show_source()函数相似,但它会删除文件里的注释和空格符。

用法:

echo php_strip_whitespace("php_script.php");

get_browser

这个函数会读取browscap.ini文件,返回浏览器兼容信息。

用法:

echo $_server['http_user_agent'];
$browser = get_browser();
print_r($browser);

memory_get_usage(),memory_get_peak_usage(),getrusage()

这些函数用来获取内存和cpu使用情况,memory_get_usage()函数返回内存使用量,memory_get_peak_usage()函数返回内存使用峰值,getrusage()返回cup使用情况,在调试php代码性能时,这些函数会给你提供一些有用信息。但有一点请注意,在这些函数中window上无效。

用法:

echo "initial: ".memory_get_usage()." bytes \n";
echo "peak: ".memory_get_peak_usage()." bytes \n";
$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);

gzcompress(), gzuncompress()

这两个函数用来压缩和解压字符串数据。它们的压缩率能达到50% 左右。另外的函数 gzencode() 和 gzdecode() 也能达到类似结果,但使用了不同的压缩算法。

用法:

$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);
$original = gzuncompress($compressed);