Going nuts with preg_replace. won't replace hashes

Hi,
this is probably one of those things where it is a real simple thing that i am just not getting.

So i have an enews system that to track links i take the content of the enews and just before sending swap the links to a redirect link with the orginal link as a variable. I do this using preg_replace and this works fine.

My problem comes in that it messes with hashes and changes %23 back to a hash. This normally isn’t a problem except that twitter uses the hash as part of a variable and it needs to be a %23 to work.

eg https://twitter.com/intent/tweet?text=this%20is%20my%20tweet%20%23something

When this goes through my redirect preg_replace it changes the %23 back to hash # which then stops that link functioning correctly and cuts the preloaded twitter post at the hash i.e. you won’t see #something on the above link.

Ok so hopefully you are still with me…

this is my code i’ve been trying (i’ve tried the preg_replace as an array as well and changed which comes first)

Any help would be great. thanks



        <?php
	  $string = '<a href="http://www.mcsuk.org?title=#something%20morehashes#">this is a link</a> with # in it';
	
	
	
	 	$url_pattern = '~<a href="~';
		$url_replacement = '<a href="http://www.mcsuk.org/redirection.php?nid='.$results['news_id'].'&amp;link=';
		
	
		
		$hash_pattern = '~#~';
		$hash_replacement = '%23';
	
		//lets change the hashes
		$str = preg_replace($hash_pattern, $hash_replacement, $new_string);
		
//throw out the string so we can check		
echo $str;
		
		echo '<br>';
		//lets now change the links
		
		$new_string = $string;
		

		
		$new_str = preg_replace($url_pattern, $url_replacement, $string);
		
		//this should be the completed sting with hashes replaced with %23 and the redirect link
		echo $new_str;
		
		?>


Do you need preg_replace? Why not use str_replace?

awesome thank you. i knew it would be something simple but i’ve spent a good couple of hours trying various things this morning.

At first str_replace didn’t work as i replaced both preg_replaces. So i tried just changing the str_replace on the hash part and that seems to be working.

Thanks you’ve saved me bumbling around for god knows how many more hours :slight_smile: