php
  • regex
  • 2014-10-29 165 views 0 likes 
    0

    我对正则表达式有疑问。我想用一个字符串中的2个字符替换一个特定的文本。如何替换字符串中的2个字符之间的特定文本

    例子:

    $my_string = "[email protected]@[email protected]@weludud"; 
    $new_text = 'replaced_text"; 
    

    在myabove字符串我想更换我的人物之间的文本@@。所以在上面的字符串中,我想用replace_text替换random_text。

    所以我的输出将是replace_text。看到演示[email protected]@[email protected]@weludud

    +0

    请显示您的正则表达式 – rnevius 2014-10-29 08:40:40

    +0

    “@@ ... @@'组合是否仅在字符串中出现一次? – Michel 2014-10-29 08:40:54

    +0

    是的米歇尔它只出现一次 – 2014-10-29 08:42:33

    回答

    0
    0
    $my_string = "[email protected]@[email protected]@weludud"; 
    $replace = 'replaced_text'; 
    $replaced_text = preg_replace('#(@)(.*)(@)#si', "$1$replace$3", $my_string); 
    echo $replaced_text; 
    

    Working demo

    2

    如果@@ text @@字符串中只出现一次,可以使用explode

    $my_string = "[email protected]@[email protected]@weludud"; 
    $new_text = 'replaced_text'; 
    $var = explode('@@',$my_string); //create an array with 3 parts, the middle one being the text to be replaced 
    
    $var[1]=$new_text; 
    
    $my_string=implode('@@',$var); 
    
    相关问题