mysql - Split text under few conditions (PHP) -
i have form input field 'text' , want create different query depending on value put in field user
if there phrase - search each word (f.e. 'hello world'):
select (...) x '%hello%' , x '%world%' etc...
if phrase in quotation marks - search whole phrase (f.e. '"hello world"'):
select (...) x '%hello world%'
and that's cool - can that.
but problem starts when have mix above functionality - f.e. if phrase 'hello world "my name is" john' - should search this:
select (...) x '%hello%' , x '%world%' , x '%my name is%' , x '%john%'
how implement such functionality , manage in php?
you use preg_match_all(...):
$text = 'lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor'; preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\s+/', $text, $matches); print_r($matches);
which produce:
array ( [0] => array ( [0] => lorem [1] => ipsum [2] => "dolor sit amet" [3] => consectetur [4] => "adipiscing \"elit" [5] => dolor ) )
and can see, accounts escaped quotes inside quoted strings.
a short explanation:
" # match character '"' (?: # start non-capture group 1 \\ # match character '\' . # match character except line breaks | # or [^\\"] # match character except '\' , '"' )* # end non-capture group 1 , repeat 0 or more times " # match character '"' | # or \s+ # match non-whitespace character: [^\s] , repeat 1 or more times
and in case of matching %22 instead of double quotes, you'd do:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\s+/', $text, $matches);
you can check this also
Comments
Post a Comment