I’m using file_get_contents to get a certain file’s contents — so far that is working.
Now I want to search the file and replace all <a href=" with <a href="site.php?url= before showing the file.
How can I do this? I know I should use some kind of str_replace or even preg_replace. But I don’t know how to actually search and do it for the file I’m getting with file_get_contents.
file_get_contentsreturns a string containing the file’s content.So, you can work in this string using whichever string manipulation function you’d want, like the ones you talked about.
Something like this, using str_replace, would probably do :
But note it will only replace the URL in the
hrefattribute when that attribute is the first one of the<atag…Using a regex might help you a bit more ; but it probably won’t be perfect either, I’m afraid…
If you are working with an HTML document and want a “full” solution, using
DOMDocument::loadHTMLand working with DOM manipulation methods might be another (a bit more complex, but probably more powerful) solution.The answers given to those two questions might also be able to help you, depending on what you are willing to do :
EDIT after seeing the comment :
If you want to replace two strings, you can pass arrays to the two first parameters of
str_replace. For instance :With that :
<a href="‘ will be replaced by ‘<a href="site.php?url=‘Pages‘ will get replaced by ‘TEST‘And, quoting the manual :
If you want to replace all instances of ‘
<a href="‘, well, it’s whatstr_replacedoes by default 🙂