I need to replace some keywords in some text which are enclosed with <p></p>. These keywords will be replaced with links. To outline the rules: 1. Replace only keywords that are within a <p> and </p> 2. Replace only keywords that are NOT with a <a> and </a> This is what I got (which performs rule 1): $patterns[$counter] = "/(<p>.*\b)(".$keyword.")(\b.*<\/p>)/isU";// $replacements[$counter] = "$1<a title=\"".$anchorText."\" href=\"".$url."\">$2</a>$3"; . . . $pageContent = preg_replace($patterns, $replacements, $pageContent); PHP: However I need to modify the regex patter to include rule 2. Examples of how this should work for keyword 'piston' and 'cylinder': It should match this in bold It should NOT match this in bold It should match this in bold It should match this in bold $10 to the person who can provide the correct regex
I think you are trying to create SEO optimization. Just create a inner expression for your pattern code, just creat a nested condition inside $keyword like , (....)
I would try something like this as your pattern: or maybe don't need all the "(" and ")" so could be simpler :
The first part of the regex would match keywords within a link as wel messing up the html. Anyway, I managed to solve it myself by breaking the regex up into several checking for all combinations of no link, link before, link after, link before and after keyword within a paragraph Question closed.