1

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.

1
  • What's the problem in detecting @[[Rameez]] ? Commented Jun 17, 2015 at 9:08

3 Answers 3

1

You could simply do:

preg_replace('/@\[\[(\w+)\]\]/', "$1", $string);

[ and ] need to be escaped because they have special meaning in a regex.
This will replace any string @[[whatever]] by whatever

Sign up to request clarification or add additional context in comments.

Comments

0

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

Regular expression visualization

(?<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);

DEMO

1 Comment

Thanks Stephen..... Awesome answer with full explanation and special thanks for letting know about the reg-ex tester demo site.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.