php- 对特定 HTML 标签应用格式

php- Apply formatting on specific HTML tags

我在呈现使用文本编辑器输入数据库的文本时遇到问题。 现在我有一些基础条件,我必须在某些特定标签上应用格式,比如 <p><h1><h2> 中是否有单词 'teacher'它应该更改为 'student'。 我不确定如何对特定 html 标签应用格式

编辑 就像我在数据库中输入了以下文本

<p>teacher</p>
<h1>parent</h1>
<h2>TEACHER</h2>
<h3>PARENT</h3>
<strong>parent</strong>

我想用 student 替换 teacher 一词,前提是 <p><h1> ] 或 <h2>

所以这是一种方法:

str_replace("<p>teacher</p>", "<p>student</p>", $yourText );

http://php.net/manual/en/function.str-replace.php

你可以使用 preg_replace:

$str = '<p>teacher is reading</p>
<h1>parent</h1>
<h2>TEACHER</h2>
<h3>PARENT</h3>
<strong>parent</strong>';

//for word in string too
//i for insensitive
$resp = preg_replace('/<(p|h1|h2)>(.*?)(teacher)(.*?)<\/(p|h1|h2)>/i','<>student<‌​/>',$str);

var_dump($resp);

回复:

<p>student</p>
<h1>parent</h1>
<h2>student</h2>
<h3>PARENT</h3>
<strong>parent</strong>

我不知道,但在 html 代码中设置了此代码 <&zwnj;&#8203;/>,结果给出 <??/(tag)>

改进代码(清理): from_gist