我正在寻找一种快速方法来替换两个标签之间的字符串中的文本。PHP之间替换标签
The string contains <!-- Model # Start --> <!-- Model # End --> Tags.
我只是想更换什么是标签之间,我相信preg_replace()
会做到这一点,但我不知道如何使它发挥作用。
我正在寻找一种快速方法来替换两个标签之间的字符串中的文本。PHP之间替换标签
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;
输出:你好,我的名字是格雷格。
这只会替换'[NAME]'的最后一个实例,也就是'[NAME] [NAME]'会输出'[NAME] ]格雷格 – webbiedave 2010-12-16 22:01:26
$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
你有一些代码来显示的例子吗? – kjy112 2010-12-16 21:40:34
http://php.net/manual/en/function.preg-replace.php – 2010-12-16 21:41:49