首页 > 解决方案 > How to replace custom tags with HTML tags?

问题描述

I want to replace(including nested) the custom tags with HTML tags along with any text in between custom tags.

For example:

<ppbold>bold</ppbold> => <b>bold</b>
<ppitalic>bold</ppitalic> => <i>italic</i>
and so on ...

Please, can anyone tell the regex for that? But keep in mind the nested tags should also be replaced properly for example:

<ppbold>bold <ppitalic>bold</ppitalic></ppbold> => <b>bold<i>italic</i></b>

It would be good to provide the regex by using the preg_match_all(), preg_match() and preg_replace() functions in PHP.

标签: phpregex

解决方案


preg_replace_callback()在这里使用

~(</?)(\w+)(>)~


PHP

<?php

$string = "<ppbold>bold <ppitalic>bold</ppitalic></ppbold>";

$replacements = ["ppbold" => "b", "ppitalic" => "i"];

$regex = "~(</?)(\w+)(>)~";
$string = preg_replace_callback(
    $regex,
    function($match) use ($replacements) {
        return $match[1] . $replacements[$match[2]] . $match[3];
    },
    $string
);

echo $string;
?>

有关表达式,请参见ideone.comregex101.com上的演示。


推荐阅读