Php 查找并重放包含链接但忽略div内容的关键字
我编写了一个函数来查找关键字并将其转换为链接,下面是整个函数:Php 查找并重放包含链接但忽略div内容的关键字,php,Php,我编写了一个函数来查找关键字并将其转换为链接,下面是整个函数: function Linkkeywords($linksArray, $content){ $links = $linksArray; $links_keys = array_keys($links); $linked = array(); $existingLinks = array(); foreach ($links_keys as $word ){ if(!in_arr
function Linkkeywords($linksArray, $content){
$links = $linksArray;
$links_keys = array_keys($links);
$linked = array();
$existingLinks = array();
foreach ($links_keys as $word ){
if(!in_array($word, $existingLinks)){
$existingLinks[] = $word;
$linked[] = '<a href="'.$links[$word].'">'.$word.'</a>';
}
}
foreach($existingLinks as $key => $word){
$c = preg_replace('|(?!<[^<>]*?)(?<![?./&])\b('.$word.')\b(?!:)(?![^<>]*?>)|iu', $linked[$key], $content,1);
}
return $c;
}//End Function Linkkeywords
$linksArray = Array ( 'hello' => 'http://hello.com' );
$content = '
<div class="alert alert-post-summary">hello world</div>
hello world
';
echo Linkkeywords($linksArray, $content);
函数链接关键字($linksArray,$content){
$links=$linksArray;
$links\u keys=数组\u keys($links);
$linked=array();
$existingLinks=array();
foreach($links\u键为$word){
如果(!in_数组($word,$existingLinks)){
$existingLinks[]=$word;
$linked[]='';
}
}
foreach($key=>$word形式的现有链接){
$c=preg_replace(“|(?!)| iu”,$linked[$key],$content,1);
}
返回$c;
}//结束函数链接关键字
$linksArray=数组('hello'=>'http://hello.com' );
$content='1
你好,世界
你好,世界
';
echo Linkkeywords($linksArray,$content);
此函数的输出如下所示:
<div class="alert alert-post-summary"><a href="http://hello.com">hello</a> world</div>
hello world
<div class="alert alert-post-summary">hello world</div>
<a href="http://hello.com">hello</a> world
世界
你好,世界
我想忽略
我喜欢,函数的输出如下:
<div class="alert alert-post-summary"><a href="http://hello.com">hello</a> world</div>
hello world
<div class="alert alert-post-summary">hello world</div>
<a href="http://hello.com">hello</a> world
你好,世界
世界
如果要确保关键字不在HTML元素中,最简单的解决方案是使用解析字符串
可以按如下方式创建DOMDocument实例:$doc=DOMDocument::loadHTML($content)代码>
然后,您可以遍历文档子项:
`
`
最后检索DOMDocument的textContent以获得字符串。
这将替换html字符串的每个直接文本子节点中的关键字。如果要确保关键字不在html元素中,最简单的解决方案是使用解析字符串
可以按如下方式创建DOMDocument实例:$doc=DOMDocument::loadHTML($content)代码>
然后,您可以遍历文档子项:
`
`
最后检索DOMDocument的textContent以获得字符串。
这将替换html字符串的每个直接文本子节点中的关键字。是否特别要求您在PHP中执行此操作?看起来JavaScript更适合这种情况。我之所以这么说是因为,$content
目前是硬编码的——直接在HTML中输出链接不是更容易吗?不,我可以使用javascript,javascript有这样的功能吗?事实上,我想把特定的关键字转换成特定的链接,你是不是特别需要在PHP中这样做?看起来JavaScript更适合这种情况。我这么说是因为$content
目前是硬编码的——直接在HTML中输出链接不是更容易吗?不,我可以使用javascript,javascript有这样的功能吗?事实上,我想把特定的关键字转换成特定的链接,不,我不想从关键字中删除HTML元素,我想将URL添加到字符串中的关键字,但除了div中带有class=“alert alert post summary”的句子之外,抱歉我误解了这个问题,我再次更改了答案我的问题不是你回答的,请仔细阅读一次我的问题此代码将关键字替换为相应的链接忽略HTML元素的文本(如您所问)否,我不想从关键字中删除HTML元素,我想将URL添加到字符串中的关键字,但div中带有class=“alert alert post summary”的句子除外对不起,我误解了问题,我更改了答案再次我的问题不是你回答的,请仔细阅读我的问题这段代码用相应的链接替换关键字忽略HTML元素的文本,就像你问的那样