<?php
$text = '="sdfsdfsdf ddsfsdf ="sdfsdfsdf ddsfsdf" dsfsdf';
$regexps = [
'/="(.*?)"/',
'/!"(.*?)"/',
'/"(.*?)"/',
'/!(.*?) /',
'/=(.*?) /',
'/ (.*?) \| (.*?) /'
];
$count = 0;
$array_replace = [];
foreach($regexps as $regexp){
getMatch($text, $regexp, $array_replace, $count);
}
$text = escapeMatchValue($text);
foreach($array_replace as $key => $item){
$text = str_replace($key, $item, $text);
}
echo $text;
function getMatch(&$string, $regexp, &$array_replace, &$count){
return $string = preg_replace_callback(
$regexp,
function($matches) use (&$array_replace, &$count){
$count++;
$array_replace['str'.$count] = str_replace($matches[1], escapeMatchValue($matches[1]),$matches[0]);
return 'str'.$count;
},
$string);
}
function escapeMatchValue($str)
{
return str_replace(
['\\', '/', '"', '(', ')', '|', '-', '!', '@', '~', '&', '^', '$', '=', '>', '<', "\x00", "\n", "\r", "\x1a"],
['\\\\', '\\/', '\\"', '\\(', '\\)', '\\|', '\\-', '\\!', '\\@', '\\~', '\\&', '\\^', '\\$', '\\=', '\\>', '\\<', "\\x00", "\\n", "\\r", "\\x1a"],
$str
);
}
$text = '="привет" !"пока"';
/*
option1 - =""
option2 - !""
option3 - ""
option4 - !
option5 - =
*/
$regexps = [
'/(="(?<option1>.*?)"|!"(?<option2>.*?)"|"(?<option3>.*?)"|!(?<option4>.*?)|=(?<option5>.*?))/',
];
foreach($regexps as $regexp){
$result = preg_match_all($regexp, $text, $match);
var_dump($match);
}
<?php
$text = '="sdfsdfsdf ddsfsdf" dsfsdf';
$regexps = [
'/="(.*?)"/',
'/!"(.*?)"/',
'/"(.*?)"/',
'/!(.*?) /',
'/=(.*?) /',
'/ (.*?) \| (.*?) /'
];
foreach($regexps as $regexp){
getMatch($text, $regexp);
}
function getMatch(&$string, $regexp){
$result = preg_match_all($regexp, $string, $match);
if($result){
var_dump($match);
}
}
preg_match() и regex-выражения + объединяющие скобки для формирования выражения.
<?php
class SearchForm {
public function search() {
//.....
if($this->query){
$query_string = $this->getMatchWithSeparator($this->query);
$query->match(new Expression(':match', ['match' => $query_string]));
}
//....
}
private function getMatchWithSeparator($string){
$separators = ['!', '"', '|', '='];
foreach($separators as $separator){
$string = str_replace($separator, '@separator@' . $separator . '@separator@', $string);
}
$array = explode('@separator@', $string);
$query = '';
foreach($array as $item){
$query .= (in_array(trim($item), $separators))? $item: Yii::$app->sphinx->escapeMatchValue($item);
}
return $query;
}
}