使用php降级字符串中的标题标记(递归地将h1转换为h2,将h2转换为h3)
我知道我们可以通过将字符串加载到使用php降级字符串中的标题标记(递归地将h1转换为h2,将h2转换为h3),php,html,xml,parsing,domdocument,Php,Html,Xml,Parsing,Domdocument,我知道我们可以通过将字符串加载到 $doc=DOMDocument::loadXML($xml\u str) 然后得到H1标签,如下所示: $list = $doc->getElementsByTagName("h1"); for ($i = 0; $i < $list->length; $i++) { print($list->item($i)->nodeValue . "<br/>\n"); } 我希望我有道理。我试图实现的是自动解析客户在C
$doc=DOMDocument::loadXML($xml\u str)代码>
然后得到H1标签,如下所示:
$list = $doc->getElementsByTagName("h1");
for ($i = 0; $i < $list->length; $i++) {
print($list->item($i)->nodeValue . "<br/>\n");
}
我希望我有道理。我试图实现的是自动解析客户在CMS中输入的标题。。。当标题已经是H1时,他们在文章中使用H1。有时,还有一个页面标题是h1,这会把整个页面的结构搞得一团糟。仅仅使用它不是更简单吗
$content=str_-ireplace(数组(“”,)、数组(“”,)、$input);
由于文章将放在更深的容器中,因此适当地设置它们的样式应该不会有问题。不过我想你已经考虑过了
我会因为建议正则表达式解析HTML而被斥责。。。但是,由于您的客户机使用CMS输入HTML,我认为输入的语法非常可靠,并且元素没有属性,所以为什么不简单地使用stru替换呢
啊,劳伦斯击败了我,这是stru-ireplace解决方案的另一个变体,但更健壮一点(考虑到h1到h100)
函数demoteHtmlHeaderTags($html)
{
$originalHeaderTags=[];
$demotedHeaderTags=[];
foreach(范围(100,1)为$index)
{
$originalHeaderTags[]='';
$originalHeaderTags[]='';
$demotedHeaderTags[]='';
$demotedHeaderTags[]='';
}
返回str_ireplace($originalHeaderTags、$demotedHeaderTags、$html);
}
是的@lawrence cherone击败了你,但你也同样受到赞赏。我觉得自己像个白痴。对当然,stru_replace会起作用。谢谢,谢谢。有时候,当你想得太难的时候,解决方案可能太简单而不易理解。谢谢如果H标记有类或其他属性,这将不起作用。@PolarTheDog很好。不要使用正则表达式或简单的字符串操作来解析或更改HTML。使用。。。很确定只升到6点?
function demoteHeadings($xml_string, $top_level='H2'){
//if string's highest heading is more than $top_level,
//we demote all headings in this html by 1 level. i.e. if
//h1 is found, all h1s, h2s and so on are demoted one level -
//and we recursively call this function again;
if($top_level_in_xml > $top_level) demoteHeadings($output, $top_level);
}
$content = str_ireplace(array('<h1>','</h1>'),array('<h2>','</h2>'),$input);
function demoteHtmlHeaderTags($html)
{
$originalHeaderTags = [];
$demotedHeaderTags = [];
foreach(range(100, 1) as $index)
{
$originalHeaderTags[] = '<h' . $index .'>';
$originalHeaderTags[] = '</h' . $index . '>';
$demotedHeaderTags[] = '<h' . ($index + 1) . '>';
$demotedHeaderTags[] = '</h' . ($index + 1) . '>';
}
return str_ireplace($originalHeaderTags, $demotedHeaderTags, $html);
}