How to determine if text string appears as a child of a named html tag(如何确定文本字符串是否显示为命名html标记的子级)
本文介绍了如何确定文本字符串是否显示为命名html标记的子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的doReplace函数中,如何确定$keyword的实例不是从关键字出现在内容中的替换点开始的命名html标记数组(h1、h2、h3、h4、h5、h6、b、u、i等)的子级?此时我不想检查嵌套标记。我认为deReplace函数内部会涉及一些递归。
function doReplace($keyword)
{
//if(!is_keyword_in_named_tag())
return ' <b>'.trim($keyword).'</b>';
}
function init()
{
$content = "This will be some xhtml formatted
content that will be resident on the page in memory";
$theContent =
preg_replace_callback("/('my test string')/i","doReplace", $content);
return $theContent;
}
因此,如果$Content变量包含.
<h1>This is my test string</h1>
那么字符串"My test string"将不会被替换。
但如果#content变量包含.
<h1>This is my test string</h1>
<div>This is my test string too <b>my test string 3</b></div>
那么替换的内容将是.
<h1>This is my test string</h1>
<div>This is <b>my test string</b> too <b>my test string 3</b></div>
推荐答案
尝试使用DOMDocument和DOMXPath:
<?php
function doReplace($html)
{
$dom = new DOMDocument();
// loadHtml() needs mb_convert_encoding() to work well with UTF-8 encoding
$dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//text()[
not(ancestor::h1) and
not(ancestor::h2) and
not(ancestor::h3) and
not(ancestor::h4) and
not(ancestor::h5) and
not(ancestor::h6) and
not(ancestor::b) and
not(ancestor::u) and
not(ancestor::i)
]') as $node)
{
$replaced = str_ireplace('my test string', '<b>my test string</b>', $node->wholeText);
$newNode = $dom->createDocumentFragment();
$newNode->appendXML($replaced);
$node->parentNode->replaceChild($newNode, $node);
}
// get only the body tag with its contents, then trim the body tag itself to get only the original content
echo mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
}
$html = '<h1>This is my test string</h1>
<h2><span>Nested my test string</span></h2>
<div>This is my test string too <b>my test string 3</b></div>';
echo doReplace($html);
这篇关于如何确定文本字符串是否显示为命名html标记的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何确定文本字符串是否显示为命名html标记的子级
基础教程推荐
猜你喜欢
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
