php - 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.
解决方案
~(</?)(\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.com和regex101.com上的演示。
推荐阅读
- android - 在片段中,使用 Parcelable 实现恢复包含另一个对象列表的对象
- windows - 无法在 Windows 上使用 LLVM 库
- firebase - Firebase 安全规则从另一个节点获取值并将其与 auth.uid 进行比较
- javascript - 在 reactjs 中编辑数组
- php - Laravel 邮件事件有一个空消息
- android - 如何将提示属性转换为 ViewModel 中的观察项
- sql - 内部连接的 SQL 列单独显示?
- oracle - PLS-00103:在预期以下情况之一时遇到符号“)”:(
- java - 如果在没有 JMSPriority 标头的情况下发送 JMS 消息会发生什么
- html - 与 NavBar 位于同一行的 FontAwesome 图标