【发布时间】:2014-06-29 08:05:41
【问题描述】:
如何将字符串中以@@开头并以@@结尾的单词替换为其他单词?
提前致谢
$str = 'This is test @@test123@@';
如何获取test123的位置并替换为另一个
【问题讨论】:
如何将字符串中以@@开头并以@@结尾的单词替换为其他单词?
提前致谢
$str = 'This is test @@test123@@';
如何获取test123的位置并替换为另一个
【问题讨论】:
这种类型的模板标签替换最好用preg_replace_callback处理。
$str = 'This is test @@test123@@. This test contains other tags like @@test321@@.';
$rendered = preg_replace_callback(
'|@@(.+?)@@|',
function ($m) {
return tag_lookup($m[1]);
},
$str
);
【讨论】:
function tag_lookup($tag) { return 'hello'; },那么所有标签都会转换为 hello。我将正则表达式修复为不那么贪婪,现在试试吧。
你最好使用正则表达式。
echo $str = preg_replace("~@@(.*?)@@~","This is the replaced text", $str);
因为您要获取内容。使用preg_match() 和相同的正则表达式。
<?php
$str = 'This is test @@test123@@';
preg_match("~@@(.*?)@@~", $str, $match);
echo $match[1]; //"prints" test123
【讨论】:
preg_match()并抓取文本,然后做一个普通的str_replace()
并不是说你不应该在这里使用正则表达式,但这里有一个替代方案:
给定:$str = 'This is test @@test123@@';
$new_str = substr($str, strpos($str, "@@")+2, (strpos($str, "@@", $start))-(strpos($str, "@@")+2));
或者,同样的事情被打破了:
$start = strpos($str, "@@")+2;
$end = strpos($str, "@@", $start);
$new_str = substr($str, $start, $end-$start);
输出:
echo $new_str; // test123
【讨论】: