Regex with variable content
I'm trying to write some kind of parser in PHP: it receives a text containing variables between #*test-var*#
, e.g.: blabla #test-var# blabla
What I'm trying to do is to adjust this text so it becomes : blabla <p>test-var</p> blabla
On top of that, the type of variable can 开发者_运维百科change, e.g.: blabla #*:test-var*# blabla
should become something like: blabla <div>test-var</div>
(I've used some HTML simple tags here (e.g. the <p>
tag) to explain it, but eventually this should become more advanced HTML)
Anyone got some suggestions?
Some simple regex will do.
$string = 'blah blah #*test-var*# blah blah';
$types = array(
array(
'/#\*(.*?)\*#/',
'<p>$1</p>'
),
array(
'/#\*:(.*?)\*#/',
'<div>$1</div>'
)
);
foreach ($types as $type) {
$string = preg_replace($type[0], $type[1], $string);
}
Edit: added support for multiple tags.
function some_kind_of_parser($input, $wrapper_tag='p', $wrapper_attributes='') {
if ($wrapper_attributes == '')
$open_tag = "<$wrapper_tag>";
else
$open_tag = "<$wrapper_tag $wrapper_attributes>";
$close_tag ="</$wrapper_tag>";
$regex = '/[^(?:#\*)]+#\*([^(#\*)]+)\*#[^(?:#\*)]+/';
return preg_replace($regex, "$open_tag$1$close_tag", $input);
}
$test = 'blah blah #*test-var*# blah blah';
echo some_kind_of_parser($test);
# => <p>test-var</p>
echo some_kind_of_parser($test, 'div', 'class="foo" id ="bar"');
# => <div class="foo" id ="bar">test-var</div>
精彩评论