您的位置:首页 > 编程语言 > PHP开发

php perl风格 正则表达式

2010-10-26 12:44 309 查看
/* 查找字符串是正则表达式的主要应用。在php中,可以作用的并且用于匹配perl风格正则表达式的
    主要函数是 preg_match()。该函数原型如下
    int preg_match(string pattern, string subject[,array matches[,int flags]])
    在subject中搜索pattern。$matches[0]将包含与整个模式匹配的文本,
    $matches[1]将包含与第一个捕获的括号中的子模式所匹配的文本。依此类推
*/
    $text = "PHP is the web scripting language of choice.";
    print("在文本/"{$text}/" 中搜索 /"php/"/n");
    if (preg_match("/php/i", $text)){    //模式定界符后面的"i"表示搜索时不区分大水写
        print "->找到一个匹配/n/n";
    }else{
        print "->未找到模式/n/n";
    }
    $text = "PHP is the website scripting language of choice.";
    print("在文本/"{$text}/" 中搜索单词 /"web/"/n");
    if(preg_match("//bweb/b/i", $text)){  //模式定界符后面的"/b"表示单词的边界,因此只有独立的单词"web"才会匹配
        print "->找到一个匹配/n/n";
    }else{
        print "->未找到模式/n/n";
    }
    print("在文本/"{$text}/" 中搜索单词 /"web/"/n");
    if(preg_match("/web/i", $text)){
        print "->找到一个匹配/n/n";
    }else{
        print "->未找到模式/n/n";
    }
    $text = "http://www.php.net/index.html";
    print("从UR/"{$text}/" 中取得主机名和域名/n");
    if(preg_match("/^(http:////)?([^//]+)/i", $text, $matches)){ //模式中圆括号括起来的为子表达式
        $host = $matches[2];
        print "->主机名为:$host/n/n";
        preg_match("/[^/.//]+/.[^/.//]+$/",$host, $matches);  //从主机名中取得后面两段
        print "->域名为:{$matches[0]}/n";
    }
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: