在 HTML 中搜索和替换单词
2022-08-30 19:18:06
我试图做的是做一个“行话破坏者”。基本上,我在数据库中有一些html和一些词汇表术语。当这个人点击行话破坏者时,它会用一个漂亮的工具提示(wztooltip)替换文本中的单词,向他们展示他们的含义。
我一直在努力解决这个问题 正则表达式 / DOMDocument - 匹配和替换不在链接中的文本
答案似乎在于simple_html_dom库,但我很难让它工作。显然,任何已经链接的单词都不会被触及。以下是我所得到的。
$html = str_get_html($article['content']);
$query_glossary = "SELECT word,glossary_term_id,info FROM glossary_terms WHERE status = 1 ORDER BY LENGTH(word) DESC";
$result_glossary = mysql_query_run($query_glossary);
while($glossary = mysql_fetch_array($result_glossary)) {
$glossary_link = SITEURL.'/glossary/term/'.string_to_url($glossary['word']).'-'.$glossary['glossary_term_id'];
if(strlen($glossary['info'])>400) {
$glossary_info = substr(strip_tags($glossary['info']),0,350).' ...<br /> <a href="'.$glossary_link.'">Read More</a>';
}
else {
$glossary_info = $glossary['info'];
}
$glossary_tip = 'href="javascript:;" onmouseout="UnTip();" class="article_jargon_highligher" onmouseover="'.tooltip_javascript('<a href="'.$glossary_link.'">'.$glossary['word'].'</a>',$glossary_info,400,1,0,1).'"';
$glossary_word = $glossary['word'];
$glossary_word = preg_quote($glossary_word,'/');
//once done we can replace the words with a nice tip
foreach ($html->find('text') as $element) {
if (!in_array($element->parent()->tag,array())) {
//problems are case aren't taken into account and grammer
$element->innertext = str_ireplace(''.$glossary['word'].' ',' <a '.$glossary_tip.' >'.$glossary['word'].'</a> ', $element->innertext);
//$element->innertext = str_ireplace(''.$glossary['word'].',',' <a '.$glossary_tip.'>'.$glossary['word'].'</a> ', $element->innertext);
//$element->innertext = preg_replace ("/\s(".$glossary_word.")\s/ise","nothing(' <a'.'$glossary_tip.'>'.'$1'.'</a> ')" , $element->innertext);
// $element->innertext = str_replace('__glossary_tip_replace__',$glossary_tip, $element->innertext);
}
}
}
$article['content'] = $html->save();