Page 1 of 1

str_replace

Posted: Sun Sep 25, 2005 9:14 pm
by phoenix121
hi
i'm kinda new to php, though i have done some programming before. what i'm trying to do, is to replace all instances of <img src="xxx"> with <img src="$address/xxx">, where xxx is the filename, and $address is the variable holding the address of the website.

can anyone help?

Posted: Sun Sep 25, 2005 9:20 pm
by feyd
str_replace() will only replace exact matches to the string you supply ($search) with the replacement argument ($replace) on the $subject.

If the string needs to be more flexible, you may need to use regular expressions (preg_replace()).

Posted: Sun Sep 25, 2005 9:20 pm
by phoenix121
The code i'm currently using is:

Code: Select all

<?php
if ($_POST['submit']) {
	$address = $_POST['address'];
	if (!$contents = readfile($address)) {
		echo "<b>Error: Cannot read file! Either file is empty or file does not exist.</b>";
		exit;
	}
	$searchstring = "src=\"";
	$replacestring = "src=\"$address";
	$contents = str_replace($searchstring, $replacestring, $contents);
	
	echo $contents;
}
?>
edit: And nothing happens! Can someone please give me some sample code?

Posted: Sun Sep 25, 2005 9:23 pm
by feyd
readfile() reads the file and outputs it directly to the output stream, you may want to use file_get_contents()

Posted: Sun Sep 25, 2005 9:30 pm
by phoenix121
thanks :D

Posted: Sun Sep 25, 2005 9:39 pm
by Jenk
You may also want to consider the security implications with using $_POST data so freely :)

With that particular script, anyone could submit the location of any of the files (that the PHP process has permissions to) on the system and your scirpt will display the contents :)

Posted: Sun Sep 25, 2005 11:23 pm
by pilau
Maybe that's what he's trying to do Jenk. Or maybe it's part of a bigger system?

Posted: Mon Sep 26, 2005 5:37 am
by phoenix121
actually, i'm just experimenting with php. it would also be great help if you could help me with my other problem ->

viewtopic.php?t=38631