preg_replace regex help, questions and issues

Hi all

Hope your all well. I was hope someone could give me a hand with this question.

I’ll explain what i need to do first.

I have a string that contains copy that will be displayed on a web page.
Now this copy could have links in it or images or any other html tag.
It also could have key words or tags within it it as well. I need to turn those tags into useful links.

For example my string could look like this.


$string = 'hello world i\'m doing some php coding using regex';

$tags[] = 'php';
$tags[] = 'regex';

Now i want the tags to be changed into links.
So i use this and limit it to the first occurrence in the string of that tag:



	foreach ($tags as $key =>$value)
	{
	$patterns[]= '/\b('.$value')\b/mi';
	$replacements[] = '<a href="#" title="title details" >'.$value.'</a>';
	}

	$string = preg_replace ($patterns, $replacements, $string, 1);


This works great to some degree how ever i need it to ignore any tags within html elements such as links or img tags so basically any thing within <></>

so if the string looked like this;



$string = 'hello <a href="#" title="#" >coding</a> world \'m doing some php coding using regex and i suck big time';


i need it to ignore the tag within the <a></a>and move onto the next instance of it.

Any help on this would be great i’m been bashing my brains over the last few days