Tuesday, August 30, 2011

Using callback function in PHP to replace strings for huge items like cover letter

PHP code:


<?php


//function to replace the patters by exact string values
function my_callback($matches) {
$data = array("name"=>"senthil kumar", "age"=>"29", "work_domain"=>"PHP", "experience"=>"6");


if (isset($data[$matches[1]])) {
// return the replacement string
return $data[$matches[1]];
} else {
return $matches[0];
}
}


// this will call my_callback() every time it sees brackets
$template = "I am [name], age of [age] working as [work_domain] developer for past [experience] year.";
$template = preg_replace_callback('/\[([\w_]+)\]/','my_callback',$template);
echo $template;

?>

Output:

        I am senthil kumar, age of 29 working as PHP developer for past 6 year.

No comments:

Post a Comment