synonymsynonyms
synonymsynonyms

Reputation: 83

Cycling through urls in a string and appending a value to it PHP regex

I have the following string for example:

Welcome to my <a href="http://example.com">site</a>. Feel free to  <a href="http://localhost.com">contact me</a>.

What technique may I use to evaluate this string to add '/id/123' at the end of both of the urls resulting in:

Welcome to my <a href="http://example.com/id/123">site</a>. Feel free to  <a href="http://localhost.com/id/123">contact me</a>.

Thanks.

Upvotes: 0

Views: 59

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

$result = preg_replace('/<a\s+href="([^"]+)"/', '<a href="\1/id/123"', $subject);

Upvotes: 0

user11977
user11977

Reputation: 1793

This should work:

$string = preg_replace('/href="([^"]*)"/','href="\\1/id/123"',$string);

Upvotes: 2

Related Questions