I have one message string e.g:
$data="Hey my dear :laugh: how are you :mmmmm: :smile: and non existing smile :go: ";
and I have smile array(for checking)
$smileys=array("laugh","mmmm","smile");
yesterday friends helped me and I convert :smile:
type to like down
$data=preg_replace("/:([a-zA-Z]+):/","<img src='images/smileys/$1.png' class='smile'>",$data);
and how can I check this smile exists or no in array?
example: http://masters.az
login:test
pass:test
code example:http://masters.az/message-3
I would implode the terms with an or
then use the found term in the replace.
$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 Demo: https://eval.in/511095
Regex101 Demo: https://regex101.com/r/hI1aX0/1
Here's a JS approach:
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);
You can use in_array() function. Explanation is here
Then you should try this:-
$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>";
}
}
reference is Here
You could use 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,"
";
Output:
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