The basic problem here is greedy matching. The ".*" is a greedy match so "m%(<a href="http://dynamodata.*/a>)%g" will match exactly once, with ".*" matching everything between the first occurrence of "<a href="http://dynamodata" and the last occurrence of "/a>". If, as in this case, you want to match the first following occurrence of "/a>" you can use the non-greedy form ".*?". So,