循环遍历字符串中的url并将值附加到PHP正则表达式

循环遍历字符串中的url并将值附加到PHP正则表达式

问题描述:

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.

我有以下字符串例如: p>

 欢迎光临 我的&lt; a href =“http://example.com”&gt;网站&lt; / a&gt;。 请随意与&lt; a href =“http://localhost.com”&gt;联系我&lt; / a&gt;。
  code>  pre> 
 
 

我可以使用哪种技术来评估 这个字符串在两个url的末尾添加'/ id / 123',结果是: p>

 欢迎使用我的&lt; a href =“http://示例。  COM / ID / 123" &GT;位点LT; / a取代。 请随意与&lt; a href =“http://localhost.com/id/123”&gt;联系我&lt; / a&gt;。
  code>  pre> 
 
 

谢谢。 div>

This should work:

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

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