Welcome to WebmasterWorld Guest from 184.108.40.206
These words are between <p></p> tags. The word is identified by having a space in front of it and after it. I only want to replace the word with the link.
This is what I have done so far (the test word is hello), but it doesn't work:
$patterns = "/<p>.+\s(hello)\s.+<\/p>/i";
$replacements = "AAA"; // for testing
$pageContent = preg_replace($patterns, $replacements, $pageContent);
Thanks in advance.
I only want to replace the word with the link.
You have to grab the rest of your pattern then and store it as well so you can use it in the replacement. Note the additional parentheses added to the pattern and the use of the variables in the replacement:
$patterns = "/(<p>.*\b)(hello)(\b.*<\/p>)/is";
$replacements = "$1AAA$3"; // for testing
I modified it a bit, so it's ungreedy as well as won't match words that are already contained in html:
$patterns = "/(<p>[^<]*\b)(hello)(\b[^>]*<\/p>)/isU";
So it will match
<p><a href="/">Hello</a> there</p>
<p><table class="hello"><tr>...</tr></table> there</p>
[edited by: eelixduppy at 6:38 am (utc) on Dec. 27, 2008]
[edit reason] disabled smileys [/edit]
[^>]*will not match on something like
<p>Hello there <b>darkage</b>!</p>I would think you will want to keep the dot metacharacter there. If not, since you are no longer using the dot metacharacter you can drop that "s" modifier.
You shouldn't need that ungreedy modifier. Were you having unexpected results without it?
I have an issue though with negating the '<' and '>'. I cant replace multiple keywords with links within the same paragraph as once the first replacement is done, it now contains <a href="" ... so all other matches on that paragraph fails.
Have to look into what's the best way to solve it (avoid replacing keywords that have already been replaced and thus are a link or in other words avoid links in links - get it? :-).
Any input ?