简体   繁体   English

php字符串替换符号和特殊字符

[英]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. 我创建了一个论坛管理页面,管理员可以立即发送所有注册成员的信息消息,并使用此@username@@useremail@提及他们的姓名或电子邮件。 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. 现在,我尝试的是替换@username@如果消息正文包含它或用于提及$_SESSION['username']任何符号,然后放出正在查看消息的当前用户的用户名。

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 我尝试这样做是可行的,但无法一次检查其他内容,例如电子邮件和全名,或者一条消息中包含2个不同的符号

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM