鉴于以下情况:
$foo = "Yo [用户 Cobb] 我听说你喜欢做梦,所以我在 yo dream 里放了一个梦想,这样你就可以一边做梦一边做梦。"
我想这样做:
$foo = bar($foo);
回声 $foo;
得到这样的东西:
Yo Cobb我听说你喜欢做梦,所以我在 yo dream 里放了一个梦想,这样你就可以一边做梦一边做梦。
我不确定该bar功能应该如何工作。我认为这对正则表达式是可行的,但我个人觉得这些很难理解。使用strpos函数是另一种方法,但我想知道是否有更好的解决方案。
伪代码很好,但实际代码将不胜感激。
编辑:
这些标签不是占位符,因为第二部分是一个变量值。
编辑:
所有 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过向交换机添加更多案例来添加更多功能。