[英]How to replace whitespaces with dashes
My idea is to remove special characters and html codes and replace the whitespaces to dashes let us doing it step by step 我的想法是删除特殊字符和html代码,并将空格替换为破折号,让我们逐步进行操作
$text = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>";
now i'm want the output become Hello-world-its-me-and-love-you
I've tired this code for removal of special characters and html codes 现在,我希望输出成为“
Hello-world-its-me-and-love-you
已经厌倦了此代码,以删除特殊字符和html代码
$array = array();
$array[0] = "/<.+?>/";
$array[1] = "/[^a-zA-Z0-9 ]/";
$textout= preg_replace($array,"",$text);
Now the output will be like this Hello world its me and love you
so is there any way i can modify this code so that the text output become exact as i do needs Hello-world-its-me-and-love-you
现在输出将像是
Hello world its me and love you
所以有什么办法可以修改此代码,以便文本输出变得精确,因为我确实需要Hello-world-its-me-and-love-you
~ thank you 〜谢谢
You're probably better off using strip_tags
to get rid of the html tags for you, then use a regexp to remove all non alphanumeric (or non-space) characters. 您最好使用
strip_tags
为您摆脱html标记,然后使用正则表达式删除所有非字母数字(或非空格)字符。 Then you can simply convert spaces to hyphens using str_replace
. 然后,您可以简单地使用
str_replace
将空格转换为连字符。 Note I also added a line to collapse multiple spaces to a single space, since that is what you did in your example. 注意,我还添加了一行以将多个空格折叠到一个空格中,因为这是您在示例中所做的。 Otherwise you get
world--its-me
instead of world-its-me
. 否则,您将获得
world--its-me
而不是world-its-me
。
<?php
$text = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>";
$text = strip_tags($text);
$text = preg_replace('/[^a-zA-Z0-9 ]/', '', $text);
//this is if you want to collapse multiple spaces to one
$text = str_replace (' ', ' ', $text);
$text = str_replace (' ', '-', $text);
?>
You could just add 您可以添加
$textout = str_replace(' ', '-', $textout);
after your last line to replace the spaces with hypens. 在最后一行之后,用连字符替换空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.