php - Warning: preg_replace(): Unknown modifier ']' -


i have following error :

warning: preg_replace(): unknown modifier ']' in xxx.php on line 38

this code on line 38 :

<?php echo str_replace("</ul></div>", "", preg_replace("<div[^>]*><ul[^>]*>", "", wp_nav_menu(array('theme_location' => 'nav', 'echo' => false)) )); ?> 

can please me fix problem?

why error occurs

in php, regular expression needs enclosed within pair of delimiters. delimiter can non-alphanumeric, non-backslash, non-whitespace character; /, #, ~ commonly used ones. note possible use bracket style delimiters opening , closing brackets starting , ending delimiter, i.e. <pattern_goes_here>, [pattern_goes_here] etc. valid.

the "unknown modifier x" error occurs in following 2 cases:

  • when regular expression missing delimiters.

  • when use delimiter inside pattern without escaping it.

in case, regular expression <div[^>]*><ul[^>]*>. regex engine considers < > regex pattern, , afterwards modifiers.

regex: <div[^>  ]*><ul[^>]*>        │     │  │          │        └──┬──┘  └────┬─────┘        pattern    modifiers 

] here unknown modifier, because appears after closing > delimiter. why php throws error.

depending on pattern, unknown modifier complaint might have been *, +, p, / or ) or other letter/symbol. imsxeadsuxju valid pcre modifiers.

how fix it

the fix easy. wrap regex pattern valid delimiters. in case, chose ~ , following:

~<div[^>]*><ul[^>]*>~ │                   │ │                   └─ ending delimiter └───────────────────── starting delimiter 

if you're receiving error despite having used delimiter, might because pattern contains unescaped occurrences of said delimiter.

or escape delimiters

/foo[^/]+bar/i throw error. can escape using \ backslash if appears anywhere within regex:

/foo[^\/]+bar/i │      │     │ └──────┼─────┴─ actual delimiters        └─────── escaped slash(/) character 

this tedious job if regex pattern contains many occurrences of delimiter character.

the cleaner way, of course, use different delimiter altogether. ideally character not appear anywhere inside regex pattern, # - #foo[^/]+bar#i.

more reading:


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -