46 个非常有用的 PHP 代码片段(6)

31. 删除文件夹内容

function Delete($path) { if (is_dir($path) === true) { $files = array_diff(scandir($path), array('.', '..')); foreach ($files as $file) { Delete(realpath($path) . 'https://www.jb51.net/' . $file); } return rmdir($path); } else if (is_file($path) === true) { return unlink($path); } return false; }


语法:

<?php $path = "images/"; Delete($path); // This will delete images folder along with its contents. ?>


32. 搜索和高亮字符串中的关键字

function highlighter_text($text, $words) { $split_words = explode( " " , $words ); foreach($split_words as $word) { $color = "#4285F4"; $text = preg_replace("|($word)|Ui" , "<span style=https://www.jb51.net/article/\"color:".$color.";\"><b>$1</b></span>" , $text ); } return $text; }

语法:

<?php $string = "I like chocolates and I like apples"; $words = "apple"; echo highlighter_text($string ,$words); ?>




33. 写入文件

<? $filename = 'blog.csv'; $fp = fopen($filename, 'w'); $output = " Hello "; $output .= " World! "; $output .= "\r\n"; fputs($fp, $output); fclose($fp); ?>


34. 根据 URL 下载图片

function imagefromURL($image,$rename) { $ch = curl_init($image); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen("$rename",'w'); fwrite($fp, $rawdata); fclose($fp); }


语法:

<?php $url = "http://koonk.com/images/logo.png"; $rename = "koonk.png"; imagefromURL($url,$rename); ?>


35. 检测 URL 是否有效

function isvalidURL($url) { $check = 0; if (filter_var($url, FILTER_VALIDATE_URL) !== false) { $check = 1; } return $check; } 语法: <?php $url = "http://koonk.com"; $check = checkvalidURL($url); echo $check; //if returns 1 then URL is valid. ?>


36. 生成二维码

function qr_code($data, $type = "TXT", $size ='150', $ec='L', $margin='0') { $types = array("URL" =--> "http://", "TEL" => "TEL:", "TXT"=>"", "EMAIL" => "MAILTO:"); if(!in_array($type,array("URL", "TEL", "TXT", "EMAIL"))) { $type = "TXT"; } if (!preg_match('/^'.$types[$type].'https://www.jb51.net/', $data)) { $data = str_replace("\\", "", $types[$type]).$data; } $ch = curl_init(); $data = urlencode($data); curl_setopt($ch, CURLOPT_URL, 'http://chart.apis.google.com/chart'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, 'chs='.$size.'x'.$size.'&cht=qr&chld='.$ec.'|'.$margin.'&chl='.$data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); curl_close($ch); return $response; }


语法:

<?php header("Content-type: image/png"); echo qr_code("http://koonk.com", "URL"); ?>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6b63572ee0f0c42def825373c5cfbc86.html