View Full Version : Replacing text with links problem

06-01-2004, 04:18 AM
What I'm doing:
I'm replacing certain words in my blog posts with links.
So lets say if I type in "larry" somewhere in my post - it will link to www.larry.com (or whatever).
Now the code I have works fine... BUT... (yes we hate the buts)

What's wrong:
lets just say... "keyword" links to www.keyword.com

now.. if is say in my post... " i like the new keyword song" - the link works perfectly fine.
but... if i use that keyword in reference to another link... its screws it up.

i like a different link with <a href="www.google.com">the word keyword in it</a>
Now.. what this will do is link the "the word" to www.google.com and the word "keyword" to www.keyword.com and do nothing with the words "in it" even though they're all in the same <a> tag.
So basically it will mess up everything after the keywords that are linked by the array in the posts...

That is what I need help with....

Here's the code:

function linkz($text) {
// Define all linkz (only www.domain.xxx - the http:// is already put in):
$alink_alink = array(
"keyword" => "www.keyword.com",
"larryjimbob" => "www.biglarrystentsale.com"

foreach($alink_alink as $alink => $thelink)
$text = preg_replace("|([\s\>])(".$alink.")([\s\<\.,;:\\/\-])|imsU" , "$1<a href=\"http://".$thelink."\" target=\"_blank\">$2</a>$3" , $text);

return $text;

add_filter('the_content', 'linkz', 13); //priority
add_filter('comment_text', 'linkz', 13); //priority

The links in there are obviously in an array - so I can list any keywords i want and thier respective links. So when i make a post - it runs it through this script and does its magik. I need to debug that one problem.
A friend said something about regex possibly - but I have no idea what that is and didnt understand it when i searched it at php.net.

thanks for the help guys/gals !

06-01-2004, 05:21 AM
that's a pain. you have to read in the preceeding link,and then when you replace, you'd put ....</a><a href="preceeding_link">

View the source code of outputted page to understand exactly what is happening.... you're esentially closing the previous tag when you create a new tag....and then you're replacing the keyword with a trailing </a> which nullfies any linkage...

06-02-2004, 07:58 PM

i understand what your saying and why it's doing that...

What i dont know how to do is - make it check to see if they keyword is already inbetween <a> tags</a> and if they are - to NOt post the link....

I dont know how to do that...

06-02-2004, 08:10 PM
I think what you want to do can be done using the ? in your Regex. Check here for a tutorial on this