Home > php教程 > php手册 > php、js、java的正则替换文本方式制作模板内容输出

php、js、java的正则替换文本方式制作模板内容输出

WBOY
Release: 2016-06-13 10:54:14
Original
1148 people have browsed it

在制作模板内容输出时,很经常会使用之类的占位符,用正则的方式很方便替换这个内容,工作中只接触到java、php、js,三种语言的简单的实现方式:

java版

import java.util.HashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

public class TestRex {

    public static void main(String[] args) {

        Map map = new HashMap();

        map.put("name", "penngo");

        map.put("date", "2013-01-17");

        Pattern p = Pattern.compile("");

        String str = ", Hello ";

        Matcher m = p.matcher(str);

        StringBuffer sb = new StringBuffer();

        boolean result = m.find();

        while (result) {

            String key = m.group(1);

            String value = map.get(key);

            m.appendReplacement(sb, value);

            result = m.find();

        }

        m.appendTail(sb);

        System.out.println(sb.toString());

    }

}

 

php版

    $data = array('name'=>'penngo', 'date'=>'2013-01-17');

    function replaceStr($key, $data){

        return $data[$key];

    }

    $str = ', Hello ';

    $str = preg_replace("//ise", "replaceStr('\\1', \$data)", $str);

    echo $str;

?>

 

js版

   

   

    var date = {'name':'penngo', 'date':'2013-01-17'};

    var str = ', Hello ';

    str = str.replace(//g, function($0, $1){

        var value = date[$1];

        return value;

    });www.2cto.com

    document.write(str);

   

    

 

运行结果输出:

2013-01-17, Hello penngo

source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template