nick
nick

Reputation: 333

Replace url strings in PHP

I have a string for example : I am a boy

I want to show this on my url for example in this way : index.php?string=I-am-a-boy

My program :

            $title = "I am a boy";

            $number_wrds = str_word_count($title);
            if($number_wrds > 1){
            $url = str_replace(' ','-',$title);
            }else{
            $url = $title;
            }

What if I have a string : Destination - Silicon Valley

If I implement the same logic my url will be : index.php?string=Destination---Silicon-Valley

But I want to show only 1 hyphen.

I want to show a hyphen instead of a plus sign..

url_encode() will eventually insert plus symbols.. So it's not helping here.

Now if I use minus symbol then if the actual string is Destination - Silicon Valley, then the url will look like Destination-Silicon-Valley and not Destination---Silicon-Valley

Check this stackoverflow question title and the url. You will know what I am saying.

Check this

Upvotes: 1

Views: 661

Answers (4)

hek2mgl
hek2mgl

Reputation: 157947

Use urlencode() to send strings along with an url:

$url = 'http://your.server.com/?string=' . urlencode($string);

In comments you told, that you don't want urlencode, you'll just replace spaces by - characters.

First, you should "just do it", the if conditional and str_word_count() is just overhead. Basically your example should look like this:

$title = "I am a boy";
$url = str_replace(' ','-', $title);

That's it.

Further you told that this would make problems if the original string already contains a -. I would use preg_replace() instead of str_replace() to solve that problem. Like this:

$string = 'Destination - Silicon Valley';
// replace spaces by hyphen and
// group multiple hyphens into a single one
$string = preg_replace('/[ -]+/', '-', $string);
echo $string; // Destination-Silicon-Valley

Upvotes: 2

iCode
iCode

Reputation: 1466

just use urlencode() and urldecode(). It’s for sending Data with GET in the URL.

Upvotes: 0

ChoiZ
ChoiZ

Reputation: 732

use urlencode:

<?php
$s = "i am a boy";
echo urlencode($s);
$s = "Destination - Silicon Valley";
echo urlencode($s);
?>

return:

i+am+a+boy
Destination+-+Silicon+Valley

and urldecode:

<?php
$s = "i+am+a+boy";
echo urldecode($s)."\n";
$s = "Destination+-+Silicon Valley";
echo urldecode($s);
?>

return:

i am a boy
Destination - Silicon Valley

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

Use preg_replace instead:

$url = preg_replace('/\s+/', '-', $title);

\s+ means "any whitespace character (\t\r\n\f (space, tab, line feed, newline)).

Upvotes: 0

Related Questions