正则表达式用于特殊模式替换

huangapple go评论59阅读模式
英文:

Regex for special pattern replacement

问题

以下是翻译的代码部分:

For a placeholder replacement with PHP I have the following search patterns:
用PHP进行占位符替换时,我有以下搜索模式:

I have the following text:
我有以下文本:

And this is my replace function
这是我的替换函数

The problem here is that only the first search pattern is found, but the patterns should be treated differently.
问题在于只找到第一个搜索模式,但应该以不同方式处理这些模式。

Currently it is so that when finding H1-(.*) both strings in $text (in the second the partial pattern) is replaced.
目前的情况是,在找到__H1-(.*)__时,$text中的两个字符串(在第二个中是部分模式)都被替换。

And another problem is that in the search text could be somethink like this
另一个问题是,在搜索文本中可能会出现类似这样的情况

in this case ther is only the first pattern found but this are two different patterns:
在这种情况下,只找到第一个模式,但这是两个不同的模式:

How can I work around something like this?
如何解决类似这样的问题?

英文:

I need help with a regex.

For a placeholder replacement with PHP I have the following search patterns:

__H1-(.*)__
__H1-(.*)-(.*)__
__H1-(.*)-(.*)-(.*)__
Etc.

I have the following text:

$text ="This is an example __H1-1__ with placeholders __H1-1-2__ that are replaced";

And this is my replace function

$text = preg_replace("/" . $placeholder . "/U", $replace_string, $text);

The problem here is that only the first search pattern is found, but the patterns should be treated differently.

Currently it is so that when finding H1-(.*) both strings in $text (in the second the partial pattern) is replaced.

And another problem is that in the search text could be somethink like this

__H1-1-2-hi____H1-1-2__

in this case ther is only the first pattern found but this are two different patterns:

__H1-1-2-hi__
__H1-1-2__

How can I work around something like this?

答案1

得分: 3

你的正则表达式存在问题,因为 .* 也会在可能的情况下捕获 -_。这不是你想要的...所以不要允许它们:

$placeholder1 = "__H1-([^-_]*)__";
$placeholder2 = "__H1-([^-_]*)-([^-_]*)__";
$placeholder3 = "__H1-([^-_]*)-([^-_]*)-([^-_]*)__";
英文:

The problem with your regex is that .* will also capture - and _ when possible. This is not what you want... so don't allow those:

$placeholder1 = "__H1-([^-_]*)__";
$placeholder2 = "__H1-([^-_]*)-([^-_]*)__";
$placeholder3 = "__H1-([^-_]*)-([^-_]*)-([^-_]*)__";

huangapple
  • 本文由 发表于 2023年2月14日 22:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75449196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定