php preg_match_all preg_replace数组问题

时间:2013-12-02 00:48:35

标签: php arrays preg-replace preg-match-all bbcode

当用户想发布笑脸时,我正在进行bb代码替换功能。

问题是,如果有人使用不存在的bb代码笑脸,则会导致空帖,因为浏览器不会显示(不存在的)表情符号。

到目前为止,这是我的代码:

// DO [:smiley:]
  $convert_smiley = preg_match_all('/\[:(.*?):\]/i', $string, $matches);

  if( $convert_smiley )
  {        
    $string = preg_replace('/\[:(.*?):\]/i', "<i class='icon-smiley-$1'></i>", $string, $convert_smiley);
  }

  return $string;

笑脸的bb代码通常看起来像[:smile:]或类似[:sad:]或类似[:happy:],依此类推。

上面的代码运行良好,直到有人发布了不存在的bb代码,所以我要求的是修复非现有的表情符号。

在示例中是否有可能创建一个数组,如array('smile', 'sad', 'happy'),只有与此数组中的一个或多个匹配的bb代码才会被转换?

因此,在修复之后,不应转换发布[:test:]或仅发布[::],并且应在转换[:happy:]时将其作为原始文本发布。

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:1)

一个简单的解决方法:

$string ="[:clap:]";

$convert_smiley = preg_match_all('/\[:(.*?):\]/i', $string, $matches);

$emoticons = array("smile","clap","sad"); //array of supported smileys

if(in_array($matches[1][0],$emoticons)){
    //smily  exists
    $string = preg_replace('/\[:(.*?):\]/i', "<i class='icon-smiley-$1'></i>", $string, $convert_smiley);
}
else{
  //smily doesn't exist
}

答案 1 :(得分:1)

好吧,第一个问题是您要将$convert_smiley设置为true的{​​{1}} / false值而不是解析结果。以下是我重写代码的方法:

preg_match_all()

请注意,我选择使用sprintf()来格式化内容&amp;将// Test strings. $string = ' [:happy:] [:frown:] [:smile:] [:foobar:]'; // Set a list of valid smileys. $valid_smileys = array('smile', 'sad', 'happy'); // Do a `preg_match_all` against the smiley’s preg_match_all('/\[:(.*?):\]/i', $string, $matches); // Check if there are matches. if (count($matches) > 0) { // Loop through the results foreach ($matches[1] as $smiley_value) { // Validate them against the valid smiley list. $pattern = $replacement = ''; if (in_array($smiley_value, $valid_smileys)) { $pattern = sprintf('/\[:%s:\]/i', $smiley_value); $replacement = sprintf("<i class='icon-smiley-%s'></i>", $smiley_value); $string = preg_replace($pattern, $replacement, $string); } } } echo 'Test Output:'; echo htmlentities($string); $pattern设置为变量。我还选择使用$replacement,因此可以轻松读取HTML DOM元素以进行调试。

答案 2 :(得分:1)

我把你可能的笑脸放在带有or符号的非分组括号中的正则表达式中:

<?php
$string = 'looks like [:smile:] or like [:sad:] or like [:happy:] [:bad-smiley:]';
$string = preg_replace('/\[:((?:smile)|(?:sad)|(?:happy)):\]/i', "<i class='icon-smiley-$1'></i>", $string);

print $string;

输出:

looks like <i class='icon-smiley-smile'></i> or like <i class='icon-smiley-sad'></i> or like <i class='icon-smiley-happy'></i> [:bad-smiley:]

[:bad-smiley:]被忽略了。

相关问题