php - Optional regex match is being ignored -


i have bit of regex in php isn't doing want to.

what want:

[segment type="segment_name"]more text here[/segment] 

to changed to:

[segmentclass='segment_name segment']more text here[/segment] 

and:

[segment]more text here[/segment] 

to changed to:

[segmentclass=' segment']more text here[/segment] 

here have:

$pattern = '/(\[segment.*?)(type=\"(.+?)\")?(.*?\[\/segment\])/is'; $replacement = '$1class=\'$3 segment\'$4'; $content = preg_replace($pattern, $replacement, $content); 

does have ideas? ? after (type=\"(.+?)\") make block optional. seems replace skipping because it's optional. think have problem greediness somewhere haven't been able sort out.

please reply if have ideas way well.

you have no closing bracket ] first segment block. because finds no match closing block, .*? matches [/segment], ignoring optional group put in there.

you should avoid using .* in form if can, , classic situation negating character class approriate. [^\]]* better choice.

the reason why character class better choice here make regex fail, instead of giving false positive.

the input have listed in question, specific matching of segment makes me believe regex overly complicated well, , replacement messy. updated regex not need dotall flag.

$pattern = '/\[segment(?: type="([^"]+)")?\]/i'; $replacement = '[segmentclass=\'$1 segment\']'; 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -