PHP 中的正则表达式模式

Regex pattern in PHP

$string= 'This is example string \add[name1]{added} and \remove[name2]{removed text} \change[name1]{this}{to}.'

这里的\add[name1]{added}应该换成added(\add=字符串被添加)

\remove[name2]{removed text} 应替换为空文本(删除 removed text

\change[name1]{this}{to}应该换成this(这里的\change表示to改为this

预期输出This is example string added and this.

我为此尝试了正则表达式,

preg_match('/\add\[name1]{(.*?)}/',$string,$match) //for add (\add)
str_replace($match[0],$match[1],$match[0])
//problem is [name] is not constant so how to get the string between
//"\add[anything]{" and "}" I will apply same regex for this
//"\remove[anything]{" and "}" too.

对于\change[anything]{string1}{string2}应替换为string1

您可以使用反向引用来做到这一点,例如</code>。请记住两次转义反斜杠,一次用于 PHP 一次用于 RegEx:</p> <pre><code><?php $string= 'This is example string ' . '\add[name1]{added} ' . 'and ' . '\remove[name2]{removed text}' . '\change[name1]{this}{to}.'; //$string = preg_replace('#\add\[.*?\]\{(.*?)\}#', '', $string); // Apply add $string = preg_replace('/\\add\[.*?\]\{(.*?)\}/', '', $string); // Apply change $string = preg_replace('/\\change\[.*?\]\{(.*?)\}\{.*?\}/', '', $string); // Apply remove $string = preg_replace('/\\remove\[.*?\]\{(.*?)\}/', '', $string); echo $string, PHP_EOL;

输出:

This is example string added and this.