gpt4 book ai didi

php - 替换所有字符直到反斜杠n次

转载 作者:可可西里 更新时间:2023-11-01 00:28:46 27 4
gpt4 key购买 nike

我有一个字符串,一个文件路径,类似

$string = "customer-service/tweep/cs/gsergsergrs/2017-20190Course-Schedule.pdf"

我想用 3 个破折号替换反斜杠之前的所有字符,以便返回:

$string = ---/---/---/---/2017-20190Course-Schedule.pdf

我试过使用这个 preg_replace 模式,但它返回 ---/2017-20190Course-Schedule.pdf

preg_replace( "/(.+\/)+/", "---/", $string);

有什么方法可以在模式匹配的每个实例上运行替换?

最佳答案

你可以使用

preg_replace('~[^/]+/~', "---/", $string);
// => ---/---/---/---/2017-20190Course-Schedule.pdf

参见 PHP demo .

参见 regex demo here .详情:

  • [^/]+ - /
  • 以外的 1 个或多个字符
  • / - 正斜杠。

请注意,/ 不必转义,因为使用了 ~ 分隔符。 preg_replace 函数用替换模式 ---/ 替换所有 非重叠事件,因此无需使用重复捕获组(如在最初的尝试中)。

关于php - 替换所有字符直到反斜杠n次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543991/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com