我有一个消息字符串 例如:
$data="Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
我有微笑数组(用于检查)
$smileys=array("laugh","mmmm","smile");
$data=preg_replace("/:([a-zA-Z]+):/","<img src='images/smileys/$1.png' class='smile'>",$data);
如何在阵列中检查这个笑脸是否存在?
示例:http://masters.az
登录:测试
传:测试
代码示例:http://masters.az/message-3
答案 0 :(得分:2)
我会用or
破坏这些条款,然后在替换中使用找到的术语。
$data = "Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
$smileys = array("laugh","mmmm","smile");
echo preg_replace('/:(' . implode('|', $smileys) . '):/', '<img src="images/smileys/$1.png" class="$1">', $data);
PHP演示:https://eval.in/511095
Regex101演示:https://regex101.com/r/hI1aX0/1
这是一种JS方法:
var test = ["laugh","mmmm","smile"];
var regex = new RegExp(':(' + test.join('|') + '):', 'g');
var string = "Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
var string = string.replace(regex, '<img src="images/smileys/$1.png" class="$1">');
console.log(string);
console.log(regex);
答案 1 :(得分:1)
您可以使用preg_replace_callback:
$data = "Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
$smileys = array("laugh","mmmm","smile");
$data = preg_replace_callback("/:([a-zA-Z]+):/",
function ($m) use($smileys) {
if (in_array($m[1], $smileys) )
return "<img src='images/smileys/$m[1].png' class='smile'>";
},
$data);
echo $data,"\n";
<强>输出:强>
Hey my dear <img src='images/smileys/laugh.png' class='smile'> how are you <img src='images/smileys/smile.png' class='smile'> and non existing smile
答案 2 :(得分:0)
您可以使用in_array()函数。解释是here
然后你应该试试这个: -
$data="Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
$smileys=array("laugh","mmmm","smile");
foreach ($smileys as $sm)
{
$data1=preg_replace("/:([a-zA-Z]+):/",$sm,"<img src='images/smileys/$1.png' class='smile'>");
if(stristr($data,$sm))
{
echo $sm." matched"."<br>";
}
}
参考是Here