我的网站上有一个关键词替换的功能。
比如说一篇文章里边有个关键词“PHP程序员”,给这个关键次替换成<a href="http://www.sina.com" target="_blank">PHP程序员</a>,下边有一个新的关键词“程序员”,这个关键词替换成<a href="http://www.baidu.com" target="_blank">程序员</a>,现在的效果是在“PHP程序员”里边的“程序员” 给了http://www.baidu.com的链接,“PHP程序员”给了sina.com的链接。
我想要的效果是只给“PHP程序员”加链接。程序员就不加了。。
求一个解决这个问题的方法。
比如说一篇文章里边有个关键词“PHP程序员”,给这个关键次替换成<a href="http://www.sina.com" target="_blank">PHP程序员</a>,下边有一个新的关键词“程序员”,这个关键词替换成<a href="http://www.baidu.com" target="_blank">程序员</a>,现在的效果是在“PHP程序员”里边的“程序员” 给了http://www.baidu.com的链接,“PHP程序员”给了sina.com的链接。
我想要的效果是只给“PHP程序员”加链接。程序员就不加了。。
求一个解决这个问题的方法。
JAVA程序员
PHP程序员
程序员然后替换:
JAVA程序员=>md5(JAVA程序员)
PHP程序员=>md5(PHP程序员)
程序员=>md5(程序员)最后再替换一次:
md5(JAVA程序员)=>JAVA程序员
md5(PHP程序员)=>PHP程序员
md5(程序员)=>程序员
preg_replace('/([^P].[^H].[^P].)程序员/','$1<a href=\'baidu.com\'>程序员<\/a>',$string))
#6 有效但太复杂其实只要注意到这样的事实:
当一轮替换后有 <a href="http://www.sina.com" target="_blank">PHP程序员</a>
只要 /程序员(?!<)/ 就可以了当然实际应用时的情况要复杂的多
如果我要替换的是“PHP程序员PHP”、“PHP程序员”、“程序员PHP”、“程序员”怎么办?
$str = preg_replace('/(程序员)(?!(:?[^<]|<(?!a)[^>]*>)*<\/a>)/imu', '<a>$1</a>', $str);echo $str;
<?php $str = '<p>元<a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">PHP程序员PHP</a><a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">PHP程序员</a>如果我要替换的是“PHP程序员PHP”、“PHP程序员”、“程序员PHP”、“程序员”怎么办<a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">程序员</a></p>';
$str = preg_replace('/(PHP程序员)(?!(:?[^<]|<(?!a)[^>]*>)*<\/a>)/imu', '<a href="http://www.sina.com" target="_blank">$1</a>', $str);echo $str;输出---------- PHP Run ----------
<p>元<a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">PHP程序员PHP</a><a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">PHP程序员</a>如果我要替换的是“<a href="http://www.sina.com" target="_blank">PHP程序员</a>PHP”、“<a href="http://www.sina.com" target="_blank">PHP程序员</a>”、“程序员PHP”、“程序员”怎么办<a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">程序员</a></p>
echo "<br>";
$pattern[0] = "/(php程序员)/";
$pattern[1] = "/((?<!php)程序员)/"; $replacement[0] = '<a href="http://www.sina.com" target="_blank">\1</a>';
$replacement[1] = '<a href="http://www.baidu.com" target="_blank">\1</a>';echo preg_replace($pattern, $replacement, $str);请看有关正向预查、反向预查的资料
你的对于这个字符串是不正确的,看清对方的需求$str = '<a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">求职程序员</a><a target="_blank" href="http://www.trjcn.com/news/news--type-list/cid-21/industry_id-14.html">程序员</a>';