Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace to insert default value when omitted

I'm trying to work on some regex for a preg_replace that would insert a default key="value" when it is not in the subject.

Here's what I have:

$pattern = '/\[section([^\]]+)(?!type)\]/i';
$replacement = '[section$1 type="wrapper"]';

I want this to turn:

[section title="This is the title"]

into:

[section title="This is the title" type="wrapper"]

but when there is a value, I don't want it to match. This means that this:

[section title="This is the title" type="full"]

would stay the same.

I am using the negative lookahead incorrectly. The first part will always match and the (?!type) becomes irrelevant. I'm not sure how to place it so that it would work. Any ideas?

like image 567
eli Avatar asked Mar 23 '23 18:03

eli


1 Answers

It should be

/\[(?![^\]]*type)section([^\]]*)\]/i
   -------------         ------
         |                  |->your required data in group 1
         |->match further only if there is no type!

try it here

like image 55
Anirudha Avatar answered Apr 06 '23 00:04

Anirudha