【问题标题】:how to replace words in a text that starts with @@ and ends with @@ with some other words?如何将文本中以@@ 开头并以@@ 结尾的单词替换为其他单词?
【发布时间】:2014-06-29 08:05:41
【问题描述】:

如何将字符串中以@@开头并以@@结尾的单词替换为其他单词? 提前致谢

$str = 'This is test @@test123@@';

如何获取test123的位置并替换为另一个

【问题讨论】:

标签: php arrays regex function


【解决方案1】:

这种类型的模板标签替换最好用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
);

【讨论】:

  • 输出为 test123@@。此测试包含其他标签,例如 @@test321
  • 如果 tag_lookup 是,例如,function tag_lookup($tag) { return 'hello'; },那么所有标签都会转换为 hello。我将正则表达式修复为不那么贪婪,现在试试吧。
【解决方案2】:

你最好使用正则表达式。

echo $str = preg_replace("~@@(.*?)@@~","This is the replaced text", $str);

Demonstration

编辑答案..正如 OP 在 unclear 上下文中提出的问题

因为您要获取内容。使用preg_match() 和相同的正则表达式。

<?php
$str = 'This is test @@test123@@';
preg_match("~@@(.*?)@@~", $str, $match);
echo $match[1]; //"prints" test123

【讨论】:

  • 我需要用@@ 包裹单词并在数据库中搜索
  • 您说如何用其他单词替换以@@ 开头并以@@ 结尾的字符串中的单词? :)
  • 那么你到底想要什么?你需要抓住 test123 吗?
  • 是的,我需要抓取该词并在数据库中搜索并替换为数据库中的数据
  • 所以首先你使用preg_match()并抓取文本,然后做一个普通的str_replace()
【解决方案3】:

并不是说你不应该在这里使用正则表达式,但这里有一个替代方案:

给定:$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

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多