1

I creating a forum admin page where admin can send all registered members info message at once and mention their name or email using this @username@ or @useremail@ and so on. Now what i tried is to replace @username@ if body of the message contain it or any of the symbol using to mention to $_SESSION['username'] and out put the username of current user that is viewing the message.

i tried doing it this was and it worked but can't check for other once like email and full name or if it contain 2 different symbol in one message

First Attempt

$match_user = str_replace("@username@",$_SESSION['username'],$string);

Here i searched online but couldn't get the exact thing i need, so i tried doing it this was but go so many errors please can someone help me out?

Second Attempt

<?php
//I use this function to check if word contain in array
 function contains($string, array $array) {
    $count = 0;
    foreach($array as $value) {
        if (false !== stripos($string,$value)) {
            ++$count;
        };
    }
    return $count == count($array);
} 
$string = Welcome @username@ we have sent you new info message at @useremail@;
$array = array('@username@', '@useremail@');

if(contains($string, $array)) {
    if($array == '@username@'){
    $match_user = str_replace("@username@",$_SESSION['username'],$string);  
    }else if($array == '@useremail@'){
    $match_user = str_replace("@useremail@",$useremail,$string);    
    }else if($array == '@fname@'){
    $match_user = str_replace("@fname@",$userfullname,$string);
    }else{
        //....
    }
}
?>
2
  • You can use arrays in str_replace. check this link Commented Sep 26, 2016 at 10:34
  • for your custom function contains there is a built in function called array_search Commented Sep 26, 2016 at 10:36

1 Answer 1

2

IN your case you can use multiple replacement in string.

Example :

$string = Welcome @username@ we have sent you new info message at @useremail@;
$array = array('@username@', '@useremail@');

$wordInString = array('@username@','@useremail@','@fname@');
$replaceInString = array($_SESSION['username'] ,$useremail,$userfullname);

$match_user = str_replace($wordInString, $replaceInString, $string);

echo $match_user;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.