Retrieve each occurrence in a string

I have a form string "a-b""c-d""e-f"... Using preg_matchhow I can extract them and get an array like:

Array
(
    [0] =>a-b
    [1] =>c-d
    [2] =>e-f
    ...
    [n-times] =>xx-zz
)

thank

+3
source share
3 answers

You can do:

$str = '"a-b""c-d""e-f"';
if(preg_match_all('/"(.*?)"/',$str,$m)) {
    var_dump($m[1]);
}

Conclusion:

array(3) {
  [0]=>
  string(3) "a-b"
  [1]=>
  string(3) "c-d"
  [2]=>
  string(3) "e-f"
}
+3
source

Regexp is not always the fastest solution:

$string = '"a-b""c-d""e-f""g-h""i-j"';
$string = trim($string, '"');
$array = explode('""',$string);
print_r($array);

Array ( [0] => a-b [1] => c-d [2] => e-f [3] => g-h [4] => i-j )
+3
source

Here I accept it.

$string = '"a-b""c-d""e-f"';

if ( preg_match_all( '/"(.*?)"/', $string, $matches ) )
{
  print_r( $matches[1] );
}

And a breakdown of the template

"   // match a double quote
(   // start a capture group
.   // match any character
*   // zero or more times
?   // but do so in an ungreedy fashion
)   // close the captured group
"   // match a double quote

The reason you are looking $matches[1], and not $matches[0], is that it preg_match_all()returns each captured group to indices 1-9, while all pattern matches have index 0. Since we only need content in the capture (in this case, the first capture group), we are looking at $matches[1].

0
source

Source: https://habr.com/ru/post/1744019/


All Articles