Home > Software design >  Negation Regular Expression
Negation Regular Expression

Time:05-04

I have a regular expression to minify the result of the code generated by Laravel's view compiler. The regular expression does nothing more than minify the HTML when compiling a view. I'm having trouble setting the regex to ignore attributes starting with ":" and "@" (eg ... @click="hide(true)" :>), since alpinejs uses them.

In the HTML code:

<select
                                        id="version-switcher"
                                        :
                                        aria-label="Localhost version"
                                        
                                        @change="window.location = $event.target.value"
                                    >
                                                                                    <option  value="https://localhost">Test</option>
                                                                                    <option selected value="https://localhost">Foo</option>
                                                                            </select>

The result should be:

<select id="version-switcher" : aria-label="Localhost version"  @change="window.location = $event.target.value"><option value="https://localhost">Test</option><option selected value="https://localhost">Foo</option></select>

However, the output is:

<select id="version-switcher": aria-label="Localhost version" @change="window.location = $event.target.value"><option value="https://localhost">Test</option><option selected value="https://localhost">Foo</option></select>

Note that the attribute starting with : and the one starting with @ are not separate from the previous attribute. The regular expression is: return preg_replace('/<!--(.*?)-->|\s\B/um', '', $html);

Can someone help me with this problem please?

CodePudding user response:

You can use

preg_replace('~<!--[^-]*(?:-(?!->)[^-]*)*-->|\s (?=\s[@:]?\w[\w-]*=|[<>])~u', '', $text)

See the regex demo.

Details:

  • <!--[^-]*(?:-(?!->)[^-]*)*--> - <!-- string, then zero or more chars other than -, then zero or more repetitions of - not immediately followed with -> and then zero or more non-hyphen chars
  • | - or
  • \s - one or more whitespaces
  • (?=\s[@:]?\w[\w-]*=|[<>]) - that are immediately followed with
    • \s[@:]?\w[\w-]*= - a whitespace, an optional @ or :, a word char, zero or more word or - chars and then a = char
    • | - or
    • [<>] - a < or > char.

CodePudding user response:

Maybe not perfect, but that could suite you:

\s(?=[\s])

Test it here: https://regex101.com/r/RADUyp/1

  • Related