use regex in php explode function

Asked

Viewed 400 times

7

I’m doing a query on my DB, and we can do an identical query on this:

"hello world" "pacific ocean"

What happens is that I can search for several strings at the same time:

Expected result:

String1: Hello World

string2: Pacific Ocean

Strings are divided by a space, but have to be in quotes.

I have the following in code:

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

The problem with this is that it will cut into the first blank space it finds instead of separating the strings. I’ve tried, too, but no result:

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

Since I don’t know the number of strings or what is written, how can I fix this?

  • 2

    Your explode is the other way around. First is the delimiter, then the word. Example: explode(' ', $search);

2 answers

4

The function explodes 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('~(["\'])([^"\']+)\1~', $str, $arr))
   print_r($arr[2]);

outworking:

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

If you want to use the function explode(), 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 it needs two other functions array_map() and str_replace()

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

  • +1 interesting! I will test here :)

  • 1

    Daniel, just a hint. Use the modifier u because of the UTF-8, the word olá lost the letter á because of the accent

  • 1

    Good tip, Wallace, good tip! I did not use the modifier because I normally test in an environment with Ncode and charset already configured, dispensing with the use of modifiers in most cases.

  • I did not know that the environment configuration did not require the use of the modifier u oo

  • Is it that regular expression that the SO makes to be able to create tags, when you ask the question? :)

3


I got what you were wanting this way:

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

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

print_r($partes);

Upshot:

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

I don’t know if it’s the most appropriate regular expression, but in it we’re using it as a word-to-stone separator", Or the asps with a space "\s+" or a space followed by an asp \s+"

Example:

http://ideone.com/H6x0j5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.