Akshay kulkarni
Akshay kulkarni

Reputation: 9

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

I have a doubt in regular expression. I want to replace a particular text which is present in 2 characters in a string.

Example:

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

In myabove string I want to replace the text between my characters @@. So in the above string I want to replace random_text with replaced_text.

So my output will be newtext!234@@replaced_text@@weludud

Upvotes: 0

Views: 60

Answers (3)

Michel
Michel

Reputation: 4157

If @@ text @@ appears only once in the string, you can use 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);

Upvotes: 2

Ali
Ali

Reputation: 3461

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

Working demo

Upvotes: 0

vks
vks

Reputation: 67968

(?<=@@)(?:(?!@@).)*(?=@@)

Try this.Replace by replace_text.See demo.

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

Upvotes: 0

Related Questions