2016-05-31 78 views
1

我试图用链接替换发布内容中的关键字,但是我意识到img标签的alt属性中的关键字也受到了影响。 有没有解决方案?顺便说一句,将码我用在的functions.php:如何替换关键字在Wordpress中的链接,而不会影响alt属性中的关键字

function replace_text_wp($text){ 
$replace = array( 
    'keyword1' => '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', 
); 
$text = str_replace(array_keys($replace), $replace, $text); 
return $text; 

}

的add_filter( 'the_content', 'replace_text_wp');

回答

0

我不得不做类似的事情不是很久以前,试试这个作为你的功能 - 它很可能会需要一些摆弄和调整,因为我适应它你的例子没有测试

function replace_text_wp($the_content){ 
    //Break up the content into parts - allowing us to just edit content and not tags 
    $parts = preg_split('/(<(?:[^"\'>]|"[^"<]*"|\'[^\'<]*\')*>)/', $the_content, -1, PREG_SPLIT_DELIM_CAPTURE); 
    // Loop through the blocks and just edit the content 
    for ($i=0, $n=count($parts); $i<$n; $i+=2) { 
     // Check if any of our keywords are within the content 
     // If so then make the keywords a link 
     $parts[$i] = str_replace('keyword1', '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', $parts[$i]); 
     } 
    } 
    // Now put it all back together 
    $the_content = implode('', $parts); 
    return $the_content; 
} 
+0

感谢西蒙,只有在正则表达式上有点变化,它的工作原理非常好 –

+0

请问您可以标记为helpfull或答案请Alan :) - 也许添加你需要的正则表达式,因为我有兴趣看到它。 –

+0

在SO上还是新的,无法标记或投票,我使用的正则表达式很简单:'code' $ parts = preg_split('/(<(?: img。* | a。*)>)/', $ text,-1,PREG_SPLIT_DELIM_CAPTURE);'code'在我的情况下,我仍然想要关键字标签等被取代 –