Preg_replace to insert default value when skipping

I am trying to work with some regular expression for preg_replace that would insert the default key = "value" if it is not in the subject.

Here is what I have:

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

I want this to work out:

 [section title="This is the title"] 

in

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

but when there is a value, I do not want it to match. This means that it is:

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

will remain the same.

I am using a negative lookahead incorrectly. The first part will always match, and (?! Type) becomes inappropriate. I am not sure how to place it so that it works. Any ideas?

+4
source share
4 answers

It should be

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

try here

+2
source
 $your_variable = str_replace('type="full" type="wrapper"]','type="full"]',preg_replace ( '/\[section([^\]]+)(?!type)\]/i' , '[section$1 type="wrapper"]' , $your_variable )); 

see here in action http://3v4l.org/6NB51

+2
source

You can use this:

 $pattern = '~\[section\b(?:[^t\]]++|t(?!ype="))*+\K]~'; $replacement = ' type="wrapper"]'; echo preg_replace($pattern, $replacement, $subject); 
+2
source

I think you are going wrong on this. Personally, I used preg_replace_callback to handle it. Sort of:

 $out = preg_replace_all( "(\\[section((\\s+\\w+=([\"'])(?:\\\\.|[^\\\\])*?\\3)*)\\s*\\])", function($m) use ($regex_attribute) { $attrs = array( "type"=>"wrapper", // you may define more defaults here ); preg_match_all("(\\s+(\\w+)=([\"'])((?:\\\\.|[^\\\\])*?)\\2)",$m,$ma,PREG_SET_ORDER); foreach($ma as $a) { $attrs[$a[1]] = $a[3]; } return // something - you can build your desired output tag using the attrs array } ); 
+1
source

Source: https://habr.com/ru/post/1483818/


All Articles