douxian7808 2012-11-13 14:23
浏览 20
已采纳

str_replace,用div替换word会导致p标记中断

The code below searches WordPress content for words and replaces these words with a link and a div. It creates a problem where the div closes the <p> tag it was inserted into.

$myposts = get_pages(args...);
$replace = array();
$i = 1;

foreach( $myposts as $post ) {
    setup_postdata($post);
    $replace[get_the_title()] = '<a href="#popupBasic' . $i . '" data-rel="popup">' . get_the_title() . '</a><div data-role="popup" class="tooltipBox" id="popupBasic' . $i . '">' . get_the_content() . '</div>';
    $i++;
}

$text = str_replace(array_keys($replace), $replace, $text);

Why is the str_replace breaking the <p> tag like this?

<div>
    <p>Some random text thats been <a href="#" class="link">cutt</a></p><div style="display: none;"><!-- placeholder --></div> off.<p></p>
</div>

If it cannot be fixed within PHP, can we fix this with jQuery? I want to put back the word thats been cut off, in this case " off." into the <p> tag that is closed after the link. And also remove the empty <p> tag in the end.

  • 写回答

1条回答 默认 最新

  • dpiz9879 2012-11-13 14:28
    关注

    p elements contain phrasing content. div is not valid in phrasing content, it's valid in flow content. (Putting a div inside a p is like putting a p inside a p.) So the browser is making the best of invalid markup.

    Try using a span rather than a div.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写