Dhruv Patel
Dhruv Patel

Reputation: 404

Regular Expression to replace a bracket with word in front when not preceded by word

I am facing problem with a regular expression.

I have a string like ('A'&'B')

Now I want to convert it to CONCAT('A'&'B') which is simple and I have done using

str_replace("(", "CONCAT(", $subject)

But I want to replace "(" to "CONCAT(" if the string doesn't have prior string "extract_json_value".

So I don't want to replace extract_json_value('A'&'B') to extract_json_valueCONCAT('A'&'B') but it will stay as it is extract_json_value('A'&'B').

Upvotes: 0

Views: 74

Answers (3)

Derek
Derek

Reputation: 3355

You can use negative lookbehind in order to match a group not preceded by a string.

First, let's have a regexp matching all strings but those containing "extract_json_value":

(?<!extract_json_value).*

Now, let's use preg_replace

$string = "extract_json_value('A'&'B')";
$pattern = '/^(?<!extract_json_value)(\(.+\))$/';
$replacement = 'CONCAT\1';
echo preg_replace($pattern, $replacement, $string);
// prints out "extract_json_value('A'&'B')"

It works too with

$string = "('A'&'B')";
...
// prints out "CONCAT('A'&'B')"

However, it does not work with

$string = "hello('A'&'B')";
...
// prints out "helloCONCAT('A'&'B')"

So, continue with a preg_replace_callback: http://php.net/manual/fr/function.preg-replace-callback.php

Upvotes: 1

hwnd
hwnd

Reputation: 70732

You could use strpos to do this.

if (strpos($subject, '(') === 0) {
  $subject = str_replace('(', 'CONCAT(', $subject);
}

If your string contains other text you can use preg_replace() and use a word boundary \B for this.

$subject = preg_replace('/\B\(/', 'CONCAT(', $subject);

Upvotes: 1

Unihedron
Unihedron

Reputation: 11051

You can expand your regex with a negative lookbehind:

(?<!extract_json_value)\(

Here is a regex demo!

Upvotes: 1

Related Questions