1

I am new to php. And I am trying to replace the "hash(#)" in the url string with "ampersand(&)".

For example:

If the url is :`

http://www.abc.com/Cat/pgecategory.aspx?cid=8730&via=top#pge=2&pgeSize=36

I want to change it to

http://www.abc.com/Cat/pgecategory.aspx?cid=8730&via=top&pge=2&pgeSize=36

I have tried the following:

str_replace("#","&",$url);

But the above doesn't work? What am I doing wrong?

How can I achieve the above task?

user2486495
  • 1,516
  • 10
  • 18
poorvank
  • 7,210
  • 17
  • 54
  • 102

4 Answers4

4

Keep in mind that str_replace returns a string. It don't change the string you passed to it.

Try,

$url = str_replace("#", "&", $url); 
echo $url;
Ahmed Siouani
  • 13,064
  • 11
  • 59
  • 70
Jite
  • 5,542
  • 2
  • 22
  • 35
3

The str_replace function returns the modified string, you have to set your url like this:

$url = str_replace("#","&",$url);
Getz
  • 3,807
  • 6
  • 33
  • 52
2

How come it didn't work. ? Have you tried outputting your result ?

<?php
$url='http://www.abc.com/Cat/pgecategory.aspx?cid=8730&via=top#pge=2&pgeSize=36';
echo $url=str_replace("#","&",$url);
Shankar Damodaran
  • 65,155
  • 42
  • 87
  • 120
0

It depends on what you are trying to do.

If you are trying to modify the URL the client requested, this is not possible.

Browsers simply do not send out the hash portion of the URL - so PHP can not even read it. However, you could read it through Javascript, with window.location.hash.

Source: Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

If you are trying to modify the URL stored in a variable, this is possible.

str_replace does not change the value of $url - it just returns the result. If you want $url to match the return value of str_replace:

$url = 'http://www.abc.com/Cat/pgecategory.aspx?cid=8730&via=top#pge=2&pgeSize=36';
$url = str_replace('#', '&', $url);

Or even shorter:

$url = str_replace('#', '&', 'http://www.abc.com/Cat/pgecategory.aspx?cid=8730&via=top#pge=2&pgeSize=36');
Community
  • 1
  • 1
Léo Lam
  • 3,375
  • 3
  • 30
  • 43