codesuck
codesuck

Reputation: 41

Php string replace for symbols and special character

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{
        //....
    }
}
?>

Upvotes: 1

Views: 587

Answers (1)

Bhavin Solanki
Bhavin Solanki

Reputation: 1364

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;

Upvotes: 2

Related Questions