Malmo
Malmo

Reputation: 13

php - replace %20, %2D in urls

Original string (How to make a sandwich?).

how to make a url that looks like this (how%20to%20make%20a%20sandwich%F2) to appear like this (how-to-make-a-sandwich?) in php.

I know that str_replace can do this but it doesn't work in all cases.

I want to use something considered as best practice and works in all cases.

Thanks!

Upvotes: 1

Views: 1507

Answers (3)

Maximo
Maximo

Reputation: 186

Well, this is the simplest, cleanest way of doing it. And it uses str_replace, of course.

$test = urldecode("how%20to%20make%20a%20sandwich%F2");
$test = str_replace(" ", "-", $test);

Upvotes: 0

sebkrueger
sebkrueger

Reputation: 386

You could use the build in php function:

$str = urldecode( string $str)

function. That convert ever %## to the corresponding char.

Upvotes: 3

preg_replace is an efficient way to do it by replacing both values at the same time:

<?php
$string = "how%20to%20make%20a%20sandwich%F2";
$find = array( '/%20/','/%F2/' );
$replace = array( '-','?' );
echo preg_replace( $find, $replace, $string );
?>

Upvotes: 1

Related Questions