[英]PHP Replace Between Tags
我正在寻找一种替换两个标签之间的字符串中的文本的快速方法。
The string contains <!-- Model # Start --> <!-- Model # End --> Tags.
我只想替换标签之间的内容,我相信preg_replace()
会做到这一点,但是我不确定如何使它起作用。
要使用preg_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;
输出:您好,我叫格雷格。
$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;
请注意,if语句将检查是否还有一个标记pos,否则,对于所有textlength-#个标记,您的起始位置0(在这种情况下为“ H”)将得到gregs :)
以上输出
Hello, my name is Greg endie ho Greg Greg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.