gpt4 book ai didi

php - 如何替换字符串中的自定义 "tags"?

转载 作者:行者123 更新时间:2023-12-04 14:19:39 26 4
gpt4 key购买 nike

鉴于以下情况:

$foo = "Yo [user Cobb] I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream."

我想这样做:

$foo = bar($foo);

echo $foo;

得到这样的东西:

Yo Cobb I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream.

我不确定 bar 函数应该如何工作。我认为这对正则表达式是可行的,但我个人觉得这些很难理解。使用 strpos function 是另一种方法,但我想知道是否有更好的解决方案。

伪代码很好,但实际代码将不胜感激。

编辑:

这些标签不是占位符,因为第二部分是一个变量值。

编辑:

所有 str_replace 答案都不正确,因为标签包含可变内容。

最佳答案

您可以使用 preg_match_all 在字符串中搜索标签。

function bar($foo)
{
$count = preg_match_all("/\[(\w+?)\s(\w+?)\]/", $foo, $matches);
if($count > 0)
{
for($i = 0; $i < $count; $i++)
{
// $matches[0][$i] contains the entire matched string
// $matches[1][$i] contains the first portion (ex: user)
// $matches[2][$i] contains the second portion (ex: Cobb)

switch($matches[1][$i])
{
case 'user':
$replacement = tag_user($matches[2][$i]);
str_replace($matches[0][$i], $replacement, $foo);
break;
}
}
}
}

现在您可以通过向开关添加更多案例来添加更多功能。

关于php - 如何替换字符串中的自定义 "tags"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com