Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用一个破折号替换多个破折号_Php_String_Str Replace - Fatal编程技术网

Php 用一个破折号替换多个破折号

Php 用一个破折号替换多个破折号,php,string,str-replace,Php,String,Str Replace,我有一个字符串,看起来像这样: something-------another--thing //^^^^^^^ ^^ 我想用一个破折号替换多个破折号 因此,预期产出为: something-another-thing //^ ^ 我试图使用str_replace(),但是我必须为每一个可能的破折号重新编写代码。那么,如何用一个破折号替换任意数量的破折号呢 对于Rizier: 尝试: $mystring = "something-----

我有一个字符串,看起来像这样:

something-------another--thing
       //^^^^^^^       ^^
我想用一个破折号替换多个破折号

因此,预期产出为:

something-another-thing
       //^       ^
我试图使用
str_replace()
,但是我必须为每一个可能的破折号重新编写代码。那么,如何用一个破折号替换任意数量的破折号呢

对于Rizier:

尝试:

 $mystring = "something-------another--thing";
 str_replace("--", "-", $mystring);
 str_replace("---", "-", $mystring);
 str_replace("----", "-", $mystring);
 str_replace("-----", "-", $mystring);
 str_replace("------", "-", $mystring);
 str_replace("-------", "-", $mystring);
 str_replace("--------", "-", $mystring);
 str_replace("---------", "-", $mystring);
 etc...

但是字符串在两个单词之间可能有10000行。

使用
preg\u replace
替换模式

$str = preg_replace('/-+/', '-', $str);
正则表达式
-+
匹配1个或多个连字符的任意序列

如果您不理解正则表达式,请阅读位于的教程。

您可以使用

<?php
$string="something-------another--thing";
echo $str = preg_replace('/-{2,}/','-',$string);

如果要清除包含多个字符的字符串,请使用以下命令:

$string="Hello,,,my text contains unused characters... What can i do???"
$newString=preg_replace('#([\-\.\?])\\1+#','$1',$string);
$string="!!!!A string with ooooother unknoooooown multiple Signs!!!!"
$newString=preg_replace('#([.])\\1+#','$1',$string);
如果要清除的字符串具有未知的多个符号,请使用以下命令:

$string="Hello,,,my text contains unused characters... What can i do???"
$newString=preg_replace('#([\-\.\?])\\1+#','$1',$string);
$string="!!!!A string with ooooother unknoooooown multiple Signs!!!!"
$newString=preg_replace('#([.])\\1+#','$1',$string);

你试过什么吗?@Rizier123他说他试过
str_replace
@Barmar我知道,但我读了太多次,OP从未用他们的尝试编辑过他们的问题。所以现在我想看看代码,而不仅仅是读“我试过了”