简体   繁体   English

如何使用Php用破折号替换所有空间?

[英]How can we replace all space with dash using Php?

How can we replace all spaces with dash '-' in Php ? 如何在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. 请改用str_replace。 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()." 它还在文档中说:“如果不需要花哨的替换规则(如正则表达式),则应始终使用此函数而不是preg_replace()”。 Your need doesn't look like to require "fancy replacing rules." 您的需求看起来并不需要“花哨的替换规则”。 So you should do 所以你应该做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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