-2

I have a requirement for which I am trying to find a regex pattern to replace the code. I understand that I can get normal regular expression for finding and replacing the text however reqirement is to find and replace the instance alternatively.

For example,

{code}
UPDATE tenants SET end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' WHERE end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' AND instance_id = '265358' AND domain = 'automobieljansen';
{code}

Rollback: 

{code}
UPDATE tenants SET end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' WHERE end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' AND instance_id = '265358' AND domain = 'automobieljansen';
{code}

This is the original text. I need to replace the first instance of the {code} to <pre> and the second instance of the {code} to </pre>

Expected result

<pre>
UPDATE tenants SET end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' WHERE end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' AND instance_id = '265358' AND domain = 'automobieljansen';
</pre>

Rollback: 

<pre>
UPDATE tenants SET end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' WHERE end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' AND instance_id = '265358' AND domain = 'automobieljansen';
</pre>

Any help on how to do this easily?

getvivekv
  • 2,193
  • 2
  • 13
  • 25

2 Answers2

1

Try the following find and replace, in regex mode:

Find:    \{code\}(.*?)\{code\}
Replace: <pre>$1</pre>

Demo

Note: I assume you would be able to run the above regex in dot all mode. If not, then do the find on this alternative pattern:

\{code\}([\s\S]*?)\{code\}
Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
1

In PHP - search for the start and end {code} and capture the text between them, outputting it between <pre> and </pre>. We use a lazy match (.*?) to ensure we don't grab all the text between the first and last {code} in the input.

echo preg_replace('/{code}(.*?){code}/s', '<pre>$1</pre>', $text);

Output:

<pre>
UPDATE tenants SET end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' WHERE end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' AND instance_id = '265358' AND domain = 'automobieljansen';
</pre>

Rollback: 

<pre>
UPDATE tenants SET end_user_uuid = '9e194bfeace6c2d17cc71cc15e84f93a' WHERE end_user_uuid = '32392464c8a19a15dd8dc982ae3d574b' AND instance_id = '265358' AND domain = 'automobieljansen';
</pre>
Nick
  • 118,076
  • 20
  • 42
  • 73