Table of Contents
比较有用的php代码片段,
一 从网页中提取关键词
二 查找页面上的所有链接
三 创建数据URI
四 下载和保存远程图片到你的服务器
五 移除Microsoft Word HTML标签
六 检测浏览器语言
七 保存请求信息到本地
八 excel相互转换日期
9 json与数据相互转换
 
Home Backend Development PHP Tutorial More useful php code snippets, _PHP tutorial

More useful php code snippets, _PHP tutorial

Jul 12, 2016 am 08:57 AM
get meta php one code Key words extract Compare fragment use Web page

比较有用的php代码片段,

一 从网页中提取关键词

$meta = get_meta_tags(<span>'</span><span>http://www.emoticode.net/</span><span>'</span><span>);
$keywords </span>= $meta[<span>'</span><span>keywords</span><span>'</span><span>];
</span><span>//</span><span> Split keywords</span>
$keywords = explode(<span>'</span><span>,</span><span>'</span><span>, $keywords );
</span><span>//</span><span> Trim them</span>
$keywords = array_map( <span>'</span><span>trim</span><span>'</span><span>, $keywords );
</span><span>//</span><span> Remove empty values</span>
$keywords =<span> array_filter( $keywords );

print_r( $keywords );</span>
Copy after login

二 查找页面上的所有链接

<span>使用DOM,你可以在任意页面上抓取链接,示例如下。

</span>
Copy after login
Copy after login

三 创建数据URI

数据URI可以帮助将图像嵌入到HTML/CSS/<span>JS中,从而节省HTTP请求。下面的函数可以利用$file创建数据URI。 

function data_uri($file, $mime) {
    $contents</span>=<span>file_get_contents($file);
    $base64</span>=<span>base64_encode($contents);
    echo </span><span>"</span><span>data:$mime;base64,$base64</span><span>"</span><span>;
}</span>
Copy after login

四 下载和保存远程图片到你的服务器

<span>当你在搭建网站时,很可能会从远程服务器上下载图片保存到你自己的服务器上,下面的代码就可以帮助你实现这个功能。

$image </span>= file_get_contents(<span>'</span><span>http://www.php100.com/image.jpg</span><span>'</span><span>);
file_put_contents(</span><span>'</span><span>/images/image.jpg</span><span>'</span>, $image);   <span>//</span><span>Where to save the image</span>
Copy after login

五 移除Microsoft Word HTML标签

<span> 当你使用Microsoft Word时,会创建很多标签tag,比如font、span、style、class等,这些标签在Word中十分有用,但当你从Word中把文本粘贴到网页上,就会出现很多没用的标签。下面实用的函数可以帮助你清除所有的Word HTML标签。

function cleanHTML($html) {
</span><span>///</span> 
<span>///</span><span> Removes all FONT and SPAN tags, and all Class and Style attributes.
</span><span>///</span><span> Designed to get rid of non-standard Microsoft Word HTML tags.
</span><span>///</span> 
<span>//</span><span> start by completely removing all unwanted tags</span>
<span>
$html </span>= ereg_replace(<span>"</span><span><(/)?(font|span|del|ins)[^>]*></span><span>"</span>,<span>""</span><span>,$html);

</span><span>//</span><span> then run another pass over the html (twice), removing unwanted attributes</span>
<span>
$html </span>= ereg_replace(<span>"</span><span><([^>]*)(class|lang|style|size|face)=(</span><span>"</span>[^<span>"</span><span>]*</span><span>"</span>|<span>'</span><span>[^</span><span>'</span>]*<span>'</span><span>|[^>]+)([^>]*)>","<\1>",$html);</span>
$html = ereg_replace(<span>"</span><span><([^>]*)(class|lang|style|size|face)=(</span><span>"</span>[^<span>"</span><span>]*</span><span>"</span>|<span>'</span><span>[^</span><span>'</span>]*<span>'</span><span>|[^>]+)([^>]*)>","<\1>",$html);</span>

<span>return</span><span> $html
}</span>
Copy after login

六 检测浏览器语言

<span>如果你的网站是多种语言的,下面的代码可以帮助你检测浏览器语言,它会返回客户端浏览器的默认语言。

function get_client_language($availableLanguages, $</span><span>default</span>=<span>'</span><span>en</span><span>'</span><span>){
    </span><span>if</span> (isset($_SERVER[<span>'</span><span>HTTP_ACCEPT_LANGUAGE</span><span>'</span><span>])) {
          $langs</span>=explode(<span>'</span><span>,</span><span>'</span>,$_SERVER[<span>'</span><span>HTTP_ACCEPT_LANGUAGE</span><span>'</span><span>]);

          </span><span>foreach</span> ($langs <span>as</span><span> $value){
              $choice</span>=substr($value,<span>0</span>,<span>2</span><span>);
              </span><span>if</span><span>(in_array($choice, $availableLanguages)){
                    </span><span>return</span><span> $choice;
              }
          }
      } 
      </span><span>return</span> $<span>default</span><span>;
}</span>
Copy after login

七 保存请求信息到本地

file_put_contents(<span>'</span><span>/tmp/all.log</span><span>'</span>,<span>'</span><span>mapping</span><span>'</span>.date(<span>"</span><span>m-d H:i:s</span><span>"</span>).<span>"</span><span>\n</span><span>"</span>,FILE_APPEND);
Copy after login

八 excel相互转换日期

<span>//如果去获取某个excel日期(格式为:2016-03-12),那么获取到的是数字,需要经过转换才能恢复<br />public</span> function excelTime($date, $time = <span>false</span><span>) {

            </span><span>if</span>(function_exists(<span>'</span><span>GregorianToJD</span><span>'</span><span>)){

                </span><span>if</span><span> (is_numeric( $date )) {

                $jd </span>= GregorianToJD( <span>1</span>, <span>1</span>, <span>1970</span><span> );

                $gregorian </span>= JDToGregorian( $jd + intval ( $date ) - <span>25569</span><span> );

                $date </span>= explode( <span>'</span><span>/</span><span>'</span><span>, $gregorian );

                $date_str </span>= str_pad( $date [<span>2</span>], <span>4</span>, <span>'</span><span>0</span><span>'</span><span>, STR_PAD_LEFT )

                .</span><span>"</span><span>-</span><span>"</span>. str_pad( $date [<span>0</span>], <span>2</span>, <span>'</span><span>0</span><span>'</span><span>, STR_PAD_LEFT )

                .</span><span>"</span><span>-</span><span>"</span>. str_pad( $date [<span>1</span>], <span>2</span>, <span>'</span><span>0</span><span>'</span><span>, STR_PAD_LEFT )

                . ($time </span>? <span>"</span><span> 00:00:00</span><span>"</span> : <span>''</span><span>);

                </span><span>return</span><span> $date_str;
                }

            }</span><span>else</span><span>{

               </span><span>//</span><span> $date=$date>25568? $date+1:25569;</span>

                <span>/*</span><span>There was a bug if Converting date before 1-1-1970 (tstamp 0)</span><span>*/</span><span>

                $ofs</span>=(<span>70</span> * <span>365</span> + <span>17</span>+<span>2</span>) * <span>86400</span><span>;

                $date </span>= date(<span>"</span><span>Y-m-d</span><span>"</span>,($date * <span>86400</span>) - $ofs).($time ? <span>"</span><span> 00:00:00</span><span>"</span> : <span>''</span><span>);
                </span><span>return</span><span> $date;
            }

    }</span>
Copy after login

9 json与数据相互转换

<span>1</span><span> json转换成数组
$json </span>= <span>'</span><span>[{"id":"22","name":"33","descn":"44"}]</span><span>'</span>; <span>//</span><span>json格式的数组转换成 php的数组</span>
$arr =<span> (Array)json_decode($json);
echo $arr[</span><span>0</span>]->id; <span>//</span><span>用对象的方式访问(这种是没有转换成数组,而是转换成对象的情况</span>
Copy after login
<span>2</span><span> 数组转换成json
$json_arr </span>= array(<span>'</span><span>WebName</span><span>'</span>=><span>'</span><span>11</span><span>'</span>,<span>'</span><span>WebSite</span><span>'</span>=><span>'</span><span>11</span><span>'</span><span>);
$php_json </span>= json_encode($json_arr); <span>//</span><span>把php数组格式转换成 json 格式的数据</span>
echo $php_json;
Copy after login

 

 

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1108335.htmlTechArticle比较有用的php代码片段, 一 从网页中提取关键词 $meta = get_meta_tags( ' http://www.emoticode.net/ ' );$keywords = $meta[ ' keywords ' ]; // Split keywords $keywo...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles