php - 将多个破折号替换为一个破折号

标签 php string str-replace

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

something-------another--thing
       //^^^^^^^       ^^

我想用一个破折号替换多个破折号。

所以预期的输出是:

something-another-thing
       //^       ^

我尝试使用 str_replace(),但我必须为每个可能的破折号重新编写代码。那么,如何用单个破折号替换任意数量的破折号呢?

对于里齐尔:

尝试过:

 $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_replace 替换模式。

$str = preg_replace('/-+/', '-', $str);

正则表达式 -+ 匹配任何 1 个或多个连字符的序列。

如果您不了解正则表达式,请阅读 www.regular-expression.info 上的教程.

关于php - 将多个破折号替换为一个破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29865520/

相关文章:

php - 从 Google+ 页面获取所有事件并访问内容

c# - string.Join - "cannot convert from IEnumerable to string[]"

c# - 如何在 C# 中删除或替换 "\"

c - 使用C替换具有更高性能的最佳方法是什么?

c - 实现 "\\"而不是 ""(空格)

php - 无法为 php 7.0 加载 mysql 扩展模块?

PHP fatal error : Can't use function return value in write context

php - 使用 php exec 从导出的 sql 创建 mysql 数据库

python - 在 PDF 文件中查找文本位置

javascript - javascript eval() 函数内的 HTML 标签