zoukankan      html  css  js  c++  java
  • PHP中正则替换函数preg_replace用法笔记

      今天应老板的需求,需要将不是我们的页面修改一个链接,用js+iframe应该也能实现,但是我想尝试一下php实现方法。

      首先你得先把别人的页面download到你的php中,实现方法可以用curl, file,这里有一篇文章写的不错 http://www.11jn.com/phpbb/viewtopic.php?f=31&t=1390,这里就不多说。

      然后就是用正则表达式找到你的链接,因为是具体的链接,就直接写了,比如百度 (http://www.baidu.com)


    下面就是主要函数 preg_replace()

    mixed preg_replace ( mixed $pattern ,     mixed $replacement ,   mixed $subject     [, int $limit = -1 [, int &$count ]] )

                               正则表达式(要被替换的)      替换的内容                     需要匹配替换的对象       可选,指定替换的个数,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换

      替换一个的实例:

            要把www.baidu.com替换成www.google.com

    $content='http://www.baidu.com';
    
    $replace=preg_replace("(http://www.baidu.com)","http://www.google.com",$content);
    echo $replace;

      替换的第二个实例:

          在一个段落中替换两个多个字段,www.baidu.com替换成www.google.com ,并且Windows替换成Linux

    $content="http://www.baidu.com on Windows.";
    $str1=array("(http://www.baidu.com)","(Windows)");
    $str2=array("http://www.google.com","Linux");
    $replace=preg_replace($str1,$str2,$content);
    echo $replace;

     
  • 相关阅读:
    什么是原型(prototype)
    angularjs input指令
    angularjs 弹出框 $modal (转)
    windows下安装wabt
    windows下安装emscripten
    windows下安装mingw
    windows下安装git
    windows下安装cmake
    windows下安装python
    trunc与round
  • 原文地址:https://www.cnblogs.com/dying/p/3712308.html
Copyright © 2011-2022 走看看