如何用其他单词替换以@@
开头和以@@
结尾的字符串中的单词?提前感谢
$str = 'This is test @@test123@@';
如何获取test123
的位置并替换为另一个
你最好使用正则表达式。
echo $str = preg_replace("~@@(.*?)@@~","This is the replaced text", $str);
示范正在编辑答案…当OP在不明确的上下文中提出问题时
因为你想要抓取内容。使用preg_match()
和相同的正则表达式
<?php
$str = 'This is test @@test123@@';
preg_match("~@@(.*?)@@~", $str, $match);
echo $match[1]; //"prints" test123
并不是说你不应该在这里使用正则表达式,但这里有一个替代方案:
给定:$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
这种类型的模板标签替换最好使用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
);