Hello, I want to build a function which replaces all the links title in a string to something this: Original: Check out my website at: <a href="test.com">Test.com</a> After Replace: Check out my website at: <a href="test.com">Test.com (Replaced)</a> Please can anyone help me, make sure that if the links contains any class or any other tag then they also replace them... like if the link is <a class="link" href="test.com">, then it must also work... Thanks..!!!
Check this out for using the DOMDocument object with PHP http://www.ultramegatech.com/blog/2009/07/modifying-templates-using-domdocument-in-php/ It should make selecting elements a hell of a lot easier and able to change them on the criteria you mentioned. Otherwise if you went the Jquery route (clientside though), it would have CSS style selectors to select the exact ones you want to alter.
Enjoy dude if you feel any problem in understanding it. just ask me i am here to help. <?php $str='Check out my website at: <a href="mjawaid.co.cc">MJawaid.Co.Cc</a>'; $replace_str="MJG"; $newstr= replace_title($str,$replace_str); echo $str; echo "<br>"; echo $newstr; function replace_title($str,$replace_str) { $a=strpos($str,'">'); $a+=2; $b=strpos($str,"</"); $str=substr_replace($str,$replace_str,$a,$b-$a); return $str; } ?> Code (markup):
Thanks Joebert i was looking for that but can you please customize your code so that it will become like this: Original: Check out my website at: <a href="test.com/mypage.html">Test Link</a> After Replace: Check out my website at: <a href="test.com/mypage.html">Test Link (http://test.com/mypage.html)</a>
$str = preg_replace('#<a([^>]+)href=([\'"])([^\2]+)\2([^>]*>)(.+?)</a>#is', '<a$1href=$2$3$2$4$5 ($3)</a>', $str); Code (markup):
what would happen if I were to move the position of the href attribute to the end or middle or somewhere out of order with the last link?
Well, looks like he just made a small mistake: $str = preg_replace('#<a(.*?)href=([\'"])([^\2]+)\2([^>]*>)(.+?)</a>#is', '<a$1href=$2$3$2$4$5 ($3)</a>', $str); PHP:
Sorry, i tried that code but that was not working... <?php $str = '<a href="http://mehdi.com">Mehdi Website</a> <a href="http://mehdi2.com">Mehdi Website2</a>'; $str = preg_replace('#<a(.*?)href=([\'"])([^\2]+)\2([^>]*>)(.+?)</a>#is', '<a$1href=$2$3$2$4$5 ($3)</a>', $str); echo $str; ?> PHP: Shows me: Mehdi Website Mehdi Website2 (http://mehdi.com">Mehdi Website
Seems like a bug to me, but third match was greedy, although I'm pretty sure it shouldn't have been Try this little fix of premiumscripts' pattern (changed ([^\2]+) to ([^\2]+?)) $str = preg_replace('#<a(.*?)href=([\'"])([^\2]+?)\2([^>]*>)(.+?)</a>#is', '<a$1href=$2$3$2$4$5 ($3)</a>', $str); PHP: