【发布时间】:2012-02-20 09:43:32
【问题描述】:
我想运行str_replace 或preg_replace,它在我的$content 中查找某些单词(在$glossary_terms 中找到)并将它们替换为链接(如<a href="/glossary/initial/term">term</a>)。
但是,$content 是完整的 HTML,我的链接/图像也受到影响,这不是我想要的。
$content 的一个例子是:
<div id="attachment_542" class="wp-caption alignleft" style="width: 135px"><a href="http://www.seriouslyfish.com/dev/wp-content/uploads/2011/12/Amazonas-English-1.jpg"><img class="size-thumbnail wp-image-542" title="Amazonas English" src="http://www.seriouslyfish.com/dev/wp-content/uploads/2011/12/Amazonas-English-1-288x381.jpg" alt="Amazonas English" width="125" height="165" /></a><p class="wp-caption-text">Amazonas Magazine - now in English!</p></div>
<p>Edited by Hans-Georg Evers, the magazine ‘Amazonas’ has been widely-regarded as among the finest regular publications in the hobby since its launch in 2005, an impressive achievment considering it’s only been published in German to date. The long-awaited English version is just about to launch, and we think a subscription should be top of any serious fishkeeper’s Xmas list…</p>
<p>The magazine is published in a bi-monthly basis and the English version launches with the January/February 2012 issue with distributors already organised in the United States, Canada, the United Kingdom, South Africa, Australia, and New Zealand. There are also mobile apps availablen which allow digital subscribers to read on portable devices.</p>
<p>It’s fair to say that there currently exists no better publication for dedicated hobbyists with each issue featuring cutting-edge articles on fishes, invertebrates, aquatic plants, field trips to tropical destinations plus the latest in husbandry and breeding breakthroughs by expert aquarists, all accompanied by excellent photography throughout.</p>
<p>U.S. residents can subscribe to the printed edition for just $29 USD per year, which also includes a free digital subscription, with the same offer available to Canadian readers for $41 USD or overseas subscribers for $49 USD. Please see the <a href="http://www.amazonasmagazine.com/">Amazonas website</a> for further information and a sample digital issue!</p>
<p>Alternatively, subscribe directly to the print version <a href="https://www.amazonascustomerservice.com/subscribe/index2.php">here</a> or digital version <a href="https://www.amazonascustomerservice.com/subscribe/digital.php">here</a>. Just gonna add this to the end of the post so I can do some testing.</p>
我遇到了this link,但我不确定这种方法是否适用于嵌套 HTML。
我有什么办法可以str_replace 或preg_replace 内容仅包含在<p> 标记中;排除任何嵌套的<a>、<img> 或<h1/2/3/4/5> 标签?
提前致谢,
【问题讨论】:
-
可能重复?我引用了该主题并表示,“不确定这种方法是否适用于嵌套 HTML”。
-
@dunc:使用
$xpath->query("//text()[not(parent::a) and contains(., '$glossary_term')]"),一切就绪。//部分负责嵌套。 -
@dunc - 显然您没有正确阅读链接的答案,接受的答案使用 DomDocument 和 XPath 来完成工作,强烈建议您甚至不要考虑使用 str_replace 或 preg_replace跨度>
-
相反,我阅读了整个线程,尤其是接受的答案。但是,我以前从未遇到过这样的功能,我不清楚它们是否会完全满足我的需要。我也不认为从 2010 年 7 月开始提出问题是谨慎或适当的。
标签: php