Php preg_replace syntax help

I need some help with replacing a string

Basically I want to display a link back to some results if the value of the referrer is a certain value.

So I get the referrer as follows:



$referer = $_SERVER['HTTP_REFERER']; 


A user could end up on this page either from a map.php page or a search.php page but I need to always return to the search.php page.

Here is what I have tried. The first part works but the code that I want to replace the string “map.php” with “search.php” doesn’t




if (stristr($referer,'search.php')) { 

				echo "<a href='$referer' title='Return to search results'>&laquo; Return to search results</a>";
				echo "<br />";
				echo "<br />";

			} else if (stristr($referer,'map.php')) {


				echo preg_replace("map.php", "search.php", $referer);

				echo "<a href='$referer' title='Return to search results'>&laquo; Return to search results</a>";
				echo "<br />";
				echo "<br />";



			}


The referrer value may be something like this



http://www.mysitename.co.uk/map.php?search=1&location=somerset&category=2&radius=0&bypass=0


Any help much appreciated.

Thanks

Paul

Doh! Sorry, I realised there is an easier function to use



$referer = str_replace("map.php", "search.php", $referer);



Paul, also bear in mind that there is a very real chance the referrer could be empty, thereby knackering your link.

Thanks Anthony again:)

Seems to be OK when the referrer is blank as it basically doesn’t display a link i.e if someone types in the link to the page



<?php

	$referer = $_SERVER['HTTP_REFERER']; 

			
	if (stristr($referer,'search.php')) { 

		echo "<a href='$referer' title='Return to search results'>&laquo; Return to search results</a>";
		echo "<br />";
		echo "<br />";

	} else if (stristr($referer,'map.php')) {

		$referer = str_replace("map.php", "search.php", $referer);				

		echo "<a href='$referer' title='Return to search results'>&laquo; Return to search results</a>";
		echo "<br />";
		echo "<br />";



	}

?>


Is this the scenario you were referring to?

It was. :slight_smile:

For future reference, the first agument of preg_replace() is a pattern typically using slashes or hashes eg.
preg_replace("/string/", …
preg_replace("#string#", …
Also note that regex rules apply, i.e. “.” is a “wildcard”.

Thanks Mittineague - I must admit I was pleased to find the simpler function but no doubt will encounter a scenario where I need preg_replace so thanks for the heads up