3v4l.org

run code in 300+ PHP versions simultaneously
<?php function parse_search($string,$quote='"') { $terms = array(); $accept = array('"','\''); if( !is_string($string) || !is_string($quote) || strlen($quote) > 1 || !in_array($quote,$accept) ) { return false; } // matches all manner of whitespace $whitespace = '/\s+/'; // what to change escaped quotes to, i.e. \' or \" $escq = '%escq%'; // ways that spaces may be encoded $encoded = array('+'); // we'll be using it a lot $space = ' '; // turn URL encoded spaces into normal ones $str = str_replace($encoded,$space,stripslashes(html_entity_decode(urldecode($string)))); // replace multiple/odd whitespace characters with single spaces $str = trim(preg_replace($whitespace,$space,$str)); // allow the user to escape quotes with backslash $str = str_replace('\\'.$quote,$escq,$str); // get the number of quotes $count = substr_count($str,$quote); // if no matching quotes, just split it if($count < 2) { return explode($space,$str); } // as long as there is a matching pair of quotes while($count > 1) { $before = strpos($str,$quote); $start = $before + 1; $end = strpos($str,$quote,$start); $after = $end + 1; $length = $end - $start; // everything before the quote $beforeStr = rtrim(substr($str,0,$before)); // break it apart, add to the terms list $terms = array_merge($terms,explode($space,$beforeStr)); // add the quote as a phrase $terms[] = trim(substr($str,$start,$length)); // trim off everything up to and including the closing quote $str = trim(substr($str,$after)); $count = substr_count($str,$quote); } // no matching quotes left, just split and add what's left $terms = array_merge($terms,explode($space,$str)); // unescape the escaped quotes foreach($terms as &$term) { $term = str_replace($escq,$quote,$term); } // remove empty entries return array_filter($terms); } $parsed = parse_search('"Cityscape"');

preferences:
59.7 ms | 402 KiB | 5 Q