use regex in explode function of php

6

I'm doing a query to my DB, and we can make an identical query to this:

  

"hello world" "pacific ocean"

What happens is that I can search multiple strings at once:

  

Expected result:

     

String1: Hello world

     

string2: pacific ocean

Strings are divided by a space, but must be enclosed in quotation marks.

I have the following code:

$array_seach = explode($search_word, " ");

The problem with this is that it will cut into the first whitespace you find, rather than separating the string. I have also tried but with no result:

$array_seach = explode($search_word, " \"");
$array_seach = explode($search_word, ' \"');

Given that I do not know the number of strings or what is written, how can I solve this?

    
asked by anonymous 17.08.2015 / 13:46

2 answers

3

I got what you were looking like this:

$string = '"palavra um" "palavra dois" "palavra três"';

$partes = preg_split('/("|"\s+|\s+")/u', $string, -1, PREG_SPLIT_NO_EMPTY);

print_r($partes);

Result:

Array
(
    [0] => palavra um
    [1] => palavra dois
    [2] => palavra três
)

I do not know if it is the most appropriate regular expression, but we are using it as a word separator for " , OR for a space with "\s+" or a space followed by a \s+"

Example:

link

    
17.08.2015 / 14:06
3

The function explode is not appropriate for this.

You can get the result you expect with the function preg_match_all

$str = '"olá mundo" "oceano pacifico"';
if (preg_match_all('~(["\'])([^"\']+)~', $str, $arr))
   print_r($arr[2]);

result:

Array
(
    [0] => olá mundo
    [1] => oceano pacifico
)

If you want to use the explode() function, see the test below, which returns the same result.

$arr = explode('" "',$str);
$arr = array_map( function($v) { return str_replace( '"', '', $v ); }, $arr);

print_r($arr);

Obviously you need two other functions array_map() and str_replace()

In particular, I find the technique with preg_match_all() safer and simpler.

    
17.08.2015 / 14:12