<?php $string = "To be escaped: + - = && || > < ! ( ) { } [ ] ^ \" ~ * ? : \ / triple ||| and split '&<&'"; print_r( [ $string, LouisBarranqueiro($string), MikkoRantalainen($string), mickmackusa($string) ] ); function LouisBarranqueiro($string) { $regex = "/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/"; $string = preg_replace_callback ($regex, function ($matches) { return "\\" . $matches[0]; }, $string); return $string; } function MikkoRantalainen($s) { static $replacements = array(); if (!$replacements) { # https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters $replacements = array( "\\" => "\\\\", # must be done first to not double encode later backslashes! "+" => "\\+", "-" => "\\-", "=" => "\\=", "&" => "\\&", "|" => "\\|", ">" => "", # cannot be safely encoded "<" => "", # cannot be safely encoded "!" => "\\!", "(" => "\\(", ")" => "\\)", "{" => "\\{", "}" => "\\}", "[" => "\\[", "]" => "\\]", "^" => "\\^", "\"" => "\\\"", "~" => "\\~", "*" => "\\*", "?" => "\\?", ":" => "\\:", "/" => "\\/", ); } return str_replace(array_keys($replacements), array_values($replacements), $s); } function mickmackusa($string) { return preg_replace( [ '_[<>]+_', // prevent hack where double-symbol is split by gt/lt symbol '_[-+=!(){}[\]^"~*?:\\/\\\\]|&(?=&)|\|(?=\|)_', ], [ '', '\\\\$0', ], $string ); }
You have javascript disabled. You will not be able to edit any code.