鉴于以下情况:
$foo = "Yo用户Cobb我听说你喜欢梦,所以我在溜溜球梦里放了一个梦,这样你就可以边做梦边做梦。“
我想这么做:
$foo = bar($foo); 回声$foo;
得到这样的东西:
哟,科布,我听说你喜欢梦,所以我把一个梦放进溜溜球梦里,这样你就可以边做梦边做梦。
我不确定bar函数应该如何工作。我认为正则表达式可以做到这一点,但我个人觉得很难理解。使用斯特波斯函数是另一种方法,但我想知道是否有更好的解决方案。
伪码是很好的,但实际的代码将不胜感激。
编辑:
这些标记不是占位符,因为第二部分是一个可变值。
编辑:
所有str_replace答案都不正确,因为标记包含可变内容。
发布于 2011-01-11 20:09:13
您可以使用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;
}
}
}
}现在,您可以通过向交换机添加更多的情况来添加更多的功能。
发布于 2011-01-11 19:58:54
由于标记包含要解析的内容,而不是要替换的静态标记,所以必须使用正则表达式。(这是最简单的方法。)
替换()是用来替换文本的正则表达式函数。
$pattern = '/\[user (\w+)\]/i';
$rpl = '<a href="http://example.com/user/${1}">${1}</a>';
return preg_replace($pattern, $rpl, $foo);这将匹配用户xy标记,其中xy是至少一个字符的单词(字-字符序列)。因为它在括号中,所以可以使用替换-字符串中的{1}访问它。$foo是要解析的字符串。返回的是带有替换标记的解析字符串。模式上的i修饰符将使匹配的大小写不敏感.如果你想让它区分大小写,就把它移走。
(从用户Cobb到维基百科url leonardo dicabrio的例子,既不符合user,也不符合Cobb。因此,无论您到了哪里,您都必须这样做(查询数据库?随便吧)。如果提供示例代码不够仔细,您可能希望指向一个静态url并向其添加部分标记内容,这就是我在这里所做的。)
发布于 2011-01-11 19:55:31
str_replace()将是您的最佳选择:
function bar($foo) {
$user = 'Cobb';
return str_replace('[user]', $user, $foo);
}
$foo = 'Yo [user] 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);
print $foo; // Will print "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."https://stackoverflow.com/questions/4661898
复制相似问题