简体   繁体   中英

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 ?

Try this...

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

OR

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

Output:

Vaghela-Nikhil

demo...

<?php

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

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

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM