Jump to content

preg_replace for 20% in url


westman

Recommended Posts

Are you sure you don't mean %20? That's the escape code for the space character in URLs.

 

There's no need for a regular expression here. Use str_replace

$new_url = str_replace('%20', ' ', $new_url);

Try: $new_url = preg_replace('/[20%]+/', ' ', $new_url);

This would cause the program to replace any sequence of any length that contains 2, 0, and % with a space. It would match things like "2%02" and "%%%"

  • Like 1
Link to comment
Share on other sites

This would cause the program to replace any sequence of any length that contains 2, 0, and % with a space. It would match things like "2%02" and "%%%"

 

 

Yes. I was thinking since a URL can contain many %20, that would be ideal (to add the character class [] ) but upon further observation it would also remove the 20 from a URL like mypage20.php for example and that's not good. So for the sake of understanding, would have this been the correct way?:

 

$new_url = preg_replace('/%20/', ' ', $new_url);

 

Thanks

Link to comment
Share on other sites

 

 

Yes. I was thinking since a URL can contain many %20, that would be ideal (to add the character class [] ) but upon further observation it would also remove the 20 from a URL like mypage20.php for example and that's not good. So for the sake of understanding, would have this been the correct way?:

 

$new_url = preg_replace('/%20/', ' ', $new_url);

 

Thanks

Yes, that would be correct. Since there are no real rules a regular expression isn't needed, you're just trying to match a literal string here.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...