1. 程式人生 > 其它 >10個你不一定知道的PHP內建函式

10個你不一定知道的PHP內建函式

PHP裡有非常豐富的內建函式,很多我們都用過,但仍有很多的函式我們大部分人都不熟悉,可它們卻十分的有用。這篇文章裡,我列舉了一些鮮為人知但會讓你眼睛一亮的PHP函式。

levenshtein()

你有沒有經歷過需要知道兩個單詞有多大的不同的時候,這個函式就是來幫你解決這個問題的。它能比較出兩個字串的不同程度。

用法:

<?php$str1="carrot";
$str2="carrrott";
echolevenshtein($str1,$str2);//Outputs2?>

get_defined_vars()

這是一個在debug除錯時非常有用的函式。這個函式返回一個多維陣列,裡面包含了所有定義過的變數。

用法:

<?phpprint_r(get_defined_vars());
?>

php_check_syntax()

這個函式非常的有用,可以用來檢查PHP的語法是否正確。出於技術上的原因,從PHP 5.05開始,這個函式被刪除了。

用法:

<?php$error_message="";
$filename="./php_script.php";
if(!php_check_syntax($filename,&$error_message)){
echo"Errorswerefoundinthefile$filename:$error_message";
}else{
echo"Thefile$filenamecontainednosyntaxerrors";
}
?>

ignore_user_abort()

這個函式用來拒絕瀏覽器端使用者終止執行指令碼的請求。正常情況下客戶端的退出會導致伺服器端指令碼停止執行。

用法:

<?phpignore_user_abort();
?>

highlight_string()

當你想把PHP程式碼顯示到頁面上時,highlight_string()函式就會顯得非常有用。這個函式會把你提供的PHP程式碼用內建的PHP語法突出顯示定義的顏色高亮顯示。這個函式有兩個引數,第一個引數是一個字串,表示這個字串需要被突出顯示。第二個引數如果設定成TRUE,這個函式就會把高亮後的程式碼當成返回值返回。

用法

<?phphighlight_string('<?phpphpinfo();?>');
?>

highlight_file

這是一個非常有用的PHP函式,它能返回指定的PHP檔案,並按照語法語義用高亮顏色突出顯示檔案內容。其中的突出顯示的程式碼都是用HTML標記處理過的。

用法:

<?phphighlight_file("php_script.php");
?>

php_strip_whitespace

這個函式也跟前面的show_source()函式相似,但它會刪除檔案裡的註釋和空格符。

用法:

<?phpechophp_strip_whitespace("php_script.php");
?>

get_browser

這個函式會讀取browscap.ini檔案,返回瀏覽器相容資訊。

用法:

<?phpecho$_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上無效。

用法:

<?phpecho"Initial:".memory_get_usage()."bytes\n";
echo"Peak:".memory_get_peak_usage()."bytes\n";
$data=getrusage();
echo"Usertime:".
($data['ru_utime.tv_sec']+
$data['ru_utime.tv_usec']/1000000);
echo"Systemtime:".
($data['ru_stime.tv_sec']+
$data['ru_stime.tv_usec']/1000000);

?>

gzcompress(), gzuncompress()

這兩個函式用來壓縮和解壓字串資料。它們的壓縮率能達到50% 左右。另外的函式 gzencode() 和 gzdecode() 也能達到類似結果,但使用了不同的壓縮演算法。

用法:

<?php$string=
"Loremipsumdolorsitamet,consectetur
adipiscingelit.Nuncutelitidmiultricies
adipiscing.Nullafacilisi.Praesentpulvinar,
sapienvelfeugiatvestibulum,nulladuipretiumorci,
nonultricieselitlacusquisante.Loremipsumdolor
sitamet,consecteturadipiscingelit.Aliquam
pretiumullamcorperurnaquisiaculis.Etiamacmassa
sedturpistemporluctus.Curabitursednibheuelit
molliscongue.Praesentipsumdiam,consecteturvitae
ornarea,aliquamanunc.Inidmagnapellentesque
tellusposuereadipiscing.Sednonmimetus,atlacinia
augue.Sedmagnanisi,ornareinmollisin,mollis
sednunc.Etiamatjustoinleoconguemollis.
Nullaminnequeegetmetushendreritscelerisque
eunonenim.Utmalesuadalacuseunullabibendum
ideuismodurnasodales.";

$compressed=gzcompress($string);
$original=gzuncompress($compressed);

?>


作者:繁花不似錦
連結:https://www.imooc.com/article/39329
來源:慕課網