str_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phoenix121
Forum Commoner
Posts: 28
Joined: Sun Sep 25, 2005 9:09 pm
Location: New Zealand

str_replace

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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()).
phoenix121
Forum Commoner
Posts: 28
Joined: Sun Sep 25, 2005 9:09 pm
Location: New Zealand

Post 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?
Last edited by phoenix121 on Sun Sep 25, 2005 9:24 pm, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

readfile() reads the file and outputs it directly to the output stream, you may want to use file_get_contents()
phoenix121
Forum Commoner
Posts: 28
Joined: Sun Sep 25, 2005 9:09 pm
Location: New Zealand

Post by phoenix121 »

thanks :D
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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 :)
pilau
Forum Regular
Posts: 594
Joined: Sat Jul 09, 2005 10:22 am
Location: Israel

Post by pilau »

Maybe that's what he's trying to do Jenk. Or maybe it's part of a bigger system?
phoenix121
Forum Commoner
Posts: 28
Joined: Sun Sep 25, 2005 9:09 pm
Location: New Zealand

Post 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
Post Reply