pairbrother Posted June 17, 2007 Share Posted June 17, 2007 Hi there, I have a a large number of pages in which I want to replace parts of links within it. Ill give an example This is the html I am getting from a function: <p>In most <a href=\"/toreplace/Bird\" title=\"Bird\">birds</a> and <a href=\"/toreplace/Reptile\" title=\"Reptile\">reptiles</a>, an <b>egg</b> is the <a href=\"/toreplace/Zygote\" title=\"Zygote\">zygote</a>, resulting from <a href=\"/toreplace/Fertilization\" title=\"Fertilization\">fertilization</a> of the <a href=\"/toreplace/Ovum\" title=\"Ovum\">ovum</a>. It nourishes and protects the <a href=\"/toreplace/Embryo\" title=\"Embryo\">embryo</a>. I want to replace all the links in it for ex: <a href=\"/toreplace/Bird\" title=\"Bird\">birds</a> with <a href=\"/Bird.html\" title=\"Bird\">birds</a> That is I want to remove the text "toreplace" and add a .html at the end of the link. I hope this is possible using php regex and I am at the right place amongst the right people. Any help would be appreciated. Thanks a lot Link to comment https://forums.phpfreaks.com/topic/55980-preg-replace-replace-links/ Share on other sites More sharing options...
Wildbug Posted June 18, 2007 Share Posted June 18, 2007 <?php $replacement = preg_quote('toreplace','|'); // Replace 'toreplace' with your string. $source = '<p>In most <a href=\"/toreplace/Bird\" title=\"Bird\">birds</a> and <a href=\"/toreplace/Reptile\" title=\"Reptile\">reptiles</a>, an <b>egg</b> is the <a href=\"/toreplace/Zygote\" title=\"Zygote\">zygote</a>, resulting from <a href=\"/toreplace/Fertilization\" title=\"Fertilization\">fertilization</a> of the <a href=\"/toreplace/Ovum\" title=\"Ovum\">ovum</a>. It nourishes and protects the <a href=\"/toreplace/Embryo\" title=\"Embryo\">embryo</a>.'; $newtext = preg_replace('|(<a href=\")' . $replacement . '(/.*?)(?=\")|i','$1$2.html',$source); ?> Birds do it. Bees do it. That should do it. Link to comment https://forums.phpfreaks.com/topic/55980-preg-replace-replace-links/#findComment-276784 Share on other sites More sharing options...
pairbrother Posted June 18, 2007 Author Share Posted June 18, 2007 nope didnt worked, gave me the same string as the source. anyways...i got it using this: preg_replace('~href="/toreplace/([^"]+)"~', 'href="/$1.html"', $test); Thanks for the reply though. Link to comment https://forums.phpfreaks.com/topic/55980-preg-replace-replace-links/#findComment-276918 Share on other sites More sharing options...
Wildbug Posted June 18, 2007 Share Posted June 18, 2007 Oh, you had your double quotes escaped in your example, so I included them in my solution, which is why it didn't work. But yours works, so no worries. Link to comment https://forums.phpfreaks.com/topic/55980-preg-replace-replace-links/#findComment-276970 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.