The replace code is replacing the whole a element content with <a rel="nofollow">
. Here’s the correction:
I used (.+?)
between <a and href"
and before and after /go/pluto/
to the closing >
. Then in the replace, we put $1 $2 $3
etc. to keep them and add rel="nofollow"
. You can check in this test, and here’s explanation about the replace.
return preg_replace('/<a(.+?)href="https://wordpress.stackexchange.com/questions/354582/(.+?)\/go\/pluto\/(.+?)"(.+?)>/', '<a$1href="$2/go/pluto/$3" rel="nofollow"$4>', $content );
Edit:
Considering there are links that contains rel attribute already, we will run regex that searches for links that does have rel but doesn’t contain nofollow and add nofollow:
return preg_replace('/<a(.+?)href="https://wordpress.stackexchange.com/questions/354582/(.+?)\/go\/pluto\/(.+?)"(.+?)rel="((?!nofollow).)*(?=")/', '$0 nofollow', $content);
I’m still figuring out the appropriate code to insert rel if the a element doesn’t contain it.