I need a regex that can replace certain words in forum posts with links (already have this regex): eregi_replace("(word)", "[url=http://link]\\1[/url]", $postText); PHP: However it should not replace words that are already in url bbcode. Eg dont replace if: [url=http://www.google.com]word[/url] [url]word[/url] PHP: Create the regex and ill paypal you $10.
Just use str_replace <?php $postText = str_replace($word, "[url=http://blah]{$word}[/url]", $postText); ?> PHP: To do it with array: <?php $words = array('word' => 'http://link', 'word' => 'http://link'); foreach($words as $word => $link) { $postText = str_replace($word, "[url={$link}]{$word}[/url]", $postText); } ?> PHP: If you want me to integrate this into your script contact me. I'll do it the way you want via PM me if interested.
Your code still doesn't solve op'c prob of not replacing the words wrapped by url tags.. Hi, DarkAge.. here is the code that doies your task. I have sent you my paypal for payment. <?php $html="testing word xyz [url=http://worst]word[/url] "; $strParts = preg_split( '/(word)/', $html,-1,PREG_SPLIT_DELIM_CAPTURE); foreach( $strParts as $key=>$part ) { if( $part=="word" && !(preg_match('/\[url=(.*?)\]$/',$strParts[$key-1] )) ) { $strParts[$key] = preg_replace( '/word/', '[url=http://replaced]word[/url]', $part ); } } $html = implode( $strParts ); echo $html; ?> PHP:
It's not a regex. It's procedure. More over it fails the following test $html="testing word xyz [url=http://worst]word blabla word[/url] "; PHP:
I can say in confirmity that no1 can do it in single regex and this is the standard procedure for it.. and with regards to that test.. u were only saying u wanted "word" wrapped by url not to be re-evaluated.. so I din't take that case.. neways.. if u need the soln in this way, I can get it for that case too... and I can assert you, no1 in the world can do that in single regex
stOK, your regex got me closer. I've modified it to this: $postText = preg_replace('{(word)(?![^\[\]]*\[/url\])}', "REPLACED", $postText); PHP: (REPLACED) is just so I can see what it is replacing. I removed the check for whitespace before and after as it would not match the word at the beginning or end of the post. However I still have 2 issues: 1. It's case sensitive where it should be insensitive 2. [url=http://www.google.com]word[/url] - OK [url]word[/url] - OK [url=http://www.word.com]blabla[/url] - FAILED (didnt include that in my op) PHP: It shouldnt match word in the last URL bbcode. Can you help me with the 2 issues ?
i think this is what you want please check preg_replace('/(word)(?!\[\/url\])/iU', 'REPLACE', '[url=http://www.google.com]word[/url] word '); PHP: