PHP在标记之间替换

PHP在标记之间替换,php,preg-replace,Php,Preg Replace,我正在寻找一种快速的方法来替换两个标记之间的字符串中的文本 The string contains <!-- Model # Start --> <!-- Model # End --> Tags. 字符串包含标记。 我只想替换标记之间的内容,我相信preg\u replace()可以做到这一点,但我不确定如何使其工作。要使用preg\u replace,请传入原始字符串和正则表达式-将返回匹配结果。关于该方法,没有什么要说的了,因为您需要了解正则表达式才能使

我正在寻找一种快速的方法来替换两个标记之间的字符串中的文本

The string contains <!-- Model # Start -->  <!-- Model # End -->  Tags.  
字符串包含标记。

我只想替换标记之间的内容,我相信
preg\u replace()
可以做到这一点,但我不确定如何使其工作。

要使用preg\u replace,请传入原始字符串和正则表达式-将返回匹配结果。关于该方法,没有什么要说的了,因为您需要了解正则表达式才能使用它

这是一个编程解决方案,可能不是最有效的代码,但它可以告诉您它在做什么

$tagOne = "[";
$tagTwo = "]";
$replacement = "Greg";

$text = "Hello, my name is [NAME]";

$startTagPos = strrpos($text, $tagOne);
$endTagPos = strrpos($text, $tagTwo);
$tagLength = $endTagPos - $startTagPos + 1;

$text = substr_replace($text, $replacement, $startTagPos, $tagLength);

echo $text;

输出:您好,我的名字是Greg。

要使用preg\u replace,请传入原始字符串和正则表达式-将返回匹配结果。关于该方法,没有什么要说的了,因为您需要了解正则表达式才能使用它

$tagOne = "[";
$tagTwo = "]";
$replacement = "Greg";

$text = "Hello, my name is [NAME] endie ho [NAME] \n [NAME]";

$textLength = strlen($text);


for ($i; $i< $textLength; $i++) {

  $startTagPos = strrpos($text, $tagOne);
  $endTagPos = strrpos($text, $tagTwo);
  $tagLength = $endTagPos - $startTagPos + 1;
  if ($startTagPos<>0) $text = substr_replace($text, $replacement, $startTagPos, $tagLength); 
}

echo $text;
这是一个编程解决方案,可能不是最有效的代码,但它可以告诉您它在做什么

$tagOne = "[";
$tagTwo = "]";
$replacement = "Greg";

$text = "Hello, my name is [NAME]";

$startTagPos = strrpos($text, $tagOne);
$endTagPos = strrpos($text, $tagTwo);
$tagLength = $endTagPos - $startTagPos + 1;

$text = substr_replace($text, $replacement, $startTagPos, $tagLength);

echo $text;

输出:您好,我的名字是Greg。

您有一些代码要显示示例吗?您有一些代码要显示示例吗?这将只替换
[name]
的最后一个实例,即,
[name][name]
将输出
[name]Greg
这将只替换
[name]
的最后一个实例,即
[name][name]
将输出
[NAME]Greg
$tagOne = "[";
$tagTwo = "]";
$replacement = "Greg";

$text = "Hello, my name is [NAME] endie ho [NAME] \n [NAME]";

$textLength = strlen($text);


for ($i; $i< $textLength; $i++) {

  $startTagPos = strrpos($text, $tagOne);
  $endTagPos = strrpos($text, $tagTwo);
  $tagLength = $endTagPos - $startTagPos + 1;
  if ($startTagPos<>0) $text = substr_replace($text, $replacement, $startTagPos, $tagLength); 
}

echo $text;