gpt4 book ai didi

php - Preg 替换直到点,包括那个

转载 作者:行者123 更新时间:2023-12-01 22:54:45 26 4
gpt4 key购买 nike

我有一行我必须替换下面的行

/myhome/ishere/where/are.you.ha

这里我有一个实时正则表达式

preg_match('/(.+\/)[^.]+(.+\.ha)/', $input_line, $output_array);

这让我活了下来

/myhome/ishere/where/.you.ha

但是我需要这样的答案

/myhome/ishere/where/you.ha

请任何人帮我删除这个点。

最佳答案

您可以这样编写模式,这将为您提供 2 个您可以使用的捕获组:

(.+\/)[^.]+\.([^.]+\.ha)$

解释

  • (.+\/) 捕获组 1,匹配 1+ 个字符,然后是最后一个 /
  • [^.]+ 匹配1+个非点
  • \. 匹配一个点
  • ([^.]+\.ha) 匹配非点,然后.ha
  • $ 字符串结束

Regex demo | Php demo

如果您在替换中使用 $1$2:

$pattern = "/(.+\/)[^.]+\.([^.]+\.ha)$/";
$s = "/myhome/ishere/where/are.you.ha";
echo preg_replace($pattern, "$1$2", $s);

输出

/myhome/ishere/where/you.ha

或参见a code an example使用带有 2 个捕获组的 preg_match。

关于php - Preg 替换直到点,包括那个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73530926/

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