Bibash Adhikari
Bibash Adhikari

Reputation: 173

How can we replace all space with dash using Php?

How can we replace all spaces with dash '-' in Php ?

So far i have tried this.

     $post_name = $row['post_name'];
     $post_name = preg_replace('/\_/', '-', $post_name);
     $post_name=  preg_replace("/[^A-Za-z 0-9?!\-]/",'',$post_name);

Now the problem is , it doesnot replace space sometimes in some string and if there is more than one space it gives more than one dash but i need only one dash . How can i solve this problem ?

Upvotes: 0

Views: 208

Answers (3)

t.m.
t.m.

Reputation: 1470

Use str_replace instead. In its document, it says Replace all occurrences of the search string with the replacement string. Which would do for you.

It also says in the document "If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace()." Your need doesn't look like to require "fancy replacing rules." So you should do

$post_name = str_replace(' ', '-', $post_name);

Upvotes: 0

Paul Z.
Paul Z.

Reputation: 905

<?php

function myfunc($post_name) {
   return preg_replace('/[\s_]+/', '-', $post_name);
}

$post_name = 'My document a_b';
echo myfunc($post_name);

?>

Upvotes: 1

Nikhil Vaghela
Nikhil Vaghela

Reputation: 2096

Try this...

echo preg_replace('/\s+/', '-', "Vaghela Nikhil");

OR

echo str_replace(" ","-","Vaghela Nikhil");

Output:

Vaghela-Nikhil

demo...

Upvotes: 1

Related Questions