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?

1
  • 1
    What is the output of var_dump($url) ? Commented Dec 23, 2013 at 9:56

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

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);

5 Comments

@Mr.Alien: echo $var = 'stuff'; is perfectly valid syntax.
@Mr.Alien, Check Jite's answer for your confusion.
@AmalMurali aaa I see, I thought it will throw an error because of echoing and assigning at the same time
@Mr.Alien: I too discovered this only recently (about 1 month back) :D
@AmalMurali there are so many things like these which are discovered by me reading questions on stack :D I thought that's not valid, so commented, anyways learnt something new again :P
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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.