I have a long string from which I want to detect and replace with some other text. Suppose my text is 'my first name is @[[Rameez]] and second name is @[[Rami]]'. I want to detect @[[Rameez]] and replace with Rameez dynamically to all likewise strings.
3 Answers
Specific version
// Find Rameez specifically
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?';
echo preg_replace($re, '$1', '**RAMEEZ** (specific)<br/>' . PHP_EOL);
Generic version
Regex
@\[\[(?<name>.+?)\]\]
Description

(?<name> .. ) represents here a named capturing group. See this answer for details.
Sample code
// Find any name enclosed by @[[ and ]].
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?';
echo preg_replace($re, '$1', '**RAMEEZ** (generic)<br/>' . PHP_EOL);
1 Comment
Rameez Rami
Thanks Stephen..... Awesome answer with full explanation and special thanks for letting know about the reg-ex tester demo site.
You can create a regex pattern then user it to match, find and replace a given string. Here's example:
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
It's C# code but you can apply it to any language really. In your case you can substitute the pattern with something like string pattern = "@[[Rameez]]"; and then use different replacement: string replacement = "Rameez";
I hope that makes sense.
@[[Rameez]]?