Php, js, java regular expression replacement text method to make the template content output _ PHP Tutorial

Source: Internet
Author: User
Make template content output by using regular expression replacement text of php, js, and java. Placeholders such as % are often used for template content output. this content can be easily replaced by regular expressions, and only java, php, and js can be used in the work, placeholders such as <% = %> are often used when making template content output in the three languages. this content can be easily replaced by regular expressions, only java, php, and js are available at work. The following three simple implementation methods are available:

Java version

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 ("<% = (\ w + ?) %> ");

String str = "<% = date %>, Hello <% = name %> ";

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 version

$ Data = array ('name' => 'penngo ', 'date' => '2017-01-17 ');

Function replaceStr ($ key, $ data ){

Return $ data [$ key];

}

$ Str = '<% = date %>, Hello <% = name %> ';

$ Str = preg_replace ("/<% = (\ w + ?) %>/Ise "," replaceStr ('\ 1', \ $ data) ", $ str );

Echo $ str;

?>

Js version

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.