Php 如何用其他单词替换以@开头、以@结尾的文本中的单词?

Php 如何用其他单词替换以@开头、以@结尾的文本中的单词?,php,arrays,regex,function,Php,Arrays,Regex,Function,如何将以@开头、以@结尾的sting中的单词替换为其他单词? 提前谢谢 $str = 'This is test @@test123@@'; 如何获得test123的位置并替换为另一个使用正则表达式更好 echo $str = preg_replace("~@@(.*?)@@~","This is the replaced text", $str); 编辑答案。。因为OP在一个不清楚的背景下提出了这个问题 因为你想抓住内容。使用preg_match()和相同的正则表达式 <?php $

如何将以
@
开头、以
@
结尾的sting中的单词替换为其他单词? 提前谢谢

$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='这是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

这种类型的模板标记替换最好使用


我需要用@来包装这个词,并在数据库中搜索它。你说过如何用其他词替换以@开头,以@结尾的sting中的词吗?:)那你到底想要什么?你需要抓取test123?是的,我需要抓取这个词并在数据库中搜索它,然后用数据库中的数据替换。因此,首先使用
preg\u match()
并抓取文本,然后执行一个正常的
str\u replace()
输出是test123@@@。此测试包含其他标记,如@@test321如果标记查找是,例如,
函数标记查找($tag){return'hello';}
则所有标记都转换为hello。我修正了正则表达式以减少贪婪,现在就试试吧。
$str = 'This is test @@test123@@.  This test contains other tags like @@test321@@.';

$rendered = preg_replace_callback(
    '|@@(.+?)@@|',
    function ($m) {
        return tag_lookup($m[1]);
    },
    $str
);