如何替换字符串中两个字符之间的特定文本


How to replace a particular text between 2 characters in a string

我对正则表达式有疑问。我想替换一个字符串中有两个字符的特定文本。

示例:

$my_string = "newtext!234@@random_text@@weludud";
$new_text  = 'replaced_text";

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

所以我的输出将是newtext!234@@replaced_text@@weludud

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

$my_string = "newtext!234@@random_text@@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);
(?<=@@)(?:(?!@@).)*(?=@@)

试试这个。替换为replace_text。请参阅演示。

http://regex101.com/r/sU3fA2/40

$my_string = "newtext!234@@random_text@@weludud";
$replace = 'replaced_text'; 
$replaced_text = preg_replace('#(@)(.*)(@)#si', "$1$replace$3", $my_string);
echo $replaced_text;

工作演示