preg_replace()无法找到结束定界符?

4

我经常使用preg_replace(),但并不是很擅长它。

如果我启动一个函数并故意输入我想要使用的所有表情符号,例如:

<?php
function parse_emotes($body){
    $body = preg_replace("#\:p#i", "<img src='images/emotes/tongue.png' alt=':p' title=':p' />", $body);
    //they continue like i said
    return $body;
}
?>

今天我试图改变一下,使用mysql让我可以随意插入和删除它们而不必在我的代码中操作。但是当我尝试时,它只会抛出如下警告:

警告: preg_replace() [function.preg-replace]: No ending delimiter '#' found in PATH/TO/FILE.php on line 226

这是我第一次使用的代码:

<?php
function parse_emotes($body){
    while($row = $db->Query("SELECT * FROM emotes", 3)) {

        return $body = preg_replace($row['regex'], "<img src='images/emotes/" . $row['src'] . "' alt='" . $row['alt'] . "' title='" . $row['alt'] . "' />", $body);
    }
}
?>

这个方法没有起作用,是的,正则表达式包含了分隔符,因此输出结果为#\:p#

我遇到了和之前相同的错误,然后我尝试从MySQL中将数据中的#移除,并且只需更改preg_replace如下:

preg_replace('#' . $row['regex'] . '#i', .......)

而它仍然不喜欢吗?我还尝试过分配:

$regex = $row['regex'];
preg_replace("#$regex#i");

你猜怎么着?还是没有结果。非常感谢任何有关该问题应该去哪里寻求帮助的建议。


这是因为您可以使用#来开始和结束一个正则表达式。您需要执行类似于“/”.$row['regex']."/"的操作。 - Matt
如果你要使用井号,那么你需要对它进行转义。可以尝试使用“||”或“{}”代替井号。另外,我假设$row['regex']只是一个井号。你真的需要使用preg_replace吗?你能否使用str_replace呢? - Matt
3
您知道由于循环内的return语句,您的代码只会尝试替换从数据库返回的第一个表情符号吗? - salathe
1
@devxdev请不要提供错误的示例。 - salathe
@DanielBrockman 需要在 preg_replace 中转义字符,因此需要转义冒号。 - dhazelett
显示剩余11条评论
2个回答

3

由于仍有人对此话题进行投票贬低。@salathe在评论中的问题是正确的(在循环中返回.. 噢哦)。

但这里是答案:

$emotes = $db->select(['regex', 'class'])->from("emotes")->execute();
while ($emote = $db->fassoc($emotes)) {
    $body = preg_replace("#{$emote['regex']}#i", "<i class='sprite-emote {$emote['class']}'></i>", $body);
}
/* ...other parsing... */
return $body;

0

将您的代码从以下内容进行更改

preg_replace('#' . $row['regex'] . '#i', .......)

preg_replace('/' . $row['regex'] . '/i', .......)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接