Regex - Get all characters after each instance of a specific character

I am very new to regex and just can't figure out how to write a pattern according to what I need. Any help would be awesome!

I want to use PHP and regex to capture each character set in the line following a specific unique character (separator), plus any character set preceding the first instance of this separator. Then I want to "combine" the desired output with an array of PHP.

  • Separator example: >
  • Example line:

    $str = 'word1 > word-2 > word.3 > word*4';
    
  • Desired match:

    array([0] => 'word1', [1] => 'word-2', [2] => 'word.3', [3] => 'word*4',);
    

I looked through the following answers, and as long as they are close, they do not quite help me in achieving what I need:

PHP, , :

function parse_conditions($str, $delimiter='>') {
if (preg_match_all('/' . $delimiter . '(.*?)' . $delimiter . '/s', $str, $matches)) {
    return $matches[1];
}

: , , (, /^(.*?)>(.*?)>(.*?)>$/)

+4
3

preg_split, http://php.net/preg_split, .

<?php
$matches = preg_split('~\s*>\s*~', 'word1 > word-2 > word.3 > word*4');
print_r($matches);

:

Array
(
    [0] => word1
    [1] => word-2
    [2] => word.3
    [3] => word*4
)

\s* .

.

<?php
$matches = explode('>', 'word1 > word-2 > word.3 > word*4');
print_r($matches);

, , :

Array
(
    [0] => word1 
    [1] =>  word-2 
    [2] =>  word.3 
    [3] =>  word*4
)
+1

array_map explode as

$str = 'word1 > word-2 > word.3 > word*4';
$result = array_map('trim',  explode('>', $str));
print_r($result);

:

Array
(
    [0] => word1
    [1] => word-2
    [2] => word.3
    [3] => word*4
)

+3

As already mentioned, you can just use explode to do this:

$str = 'word1 > word-2 > word.3 > word*4';
print_r(explode(" > " , $str));

However, for completeness, also use RegEx.

In this case, we can say that the regular expression groups all characters together that are not spaces and are not a separator >:

preg_match_all('/([^>\s]+)/', $str, $matches);
echo print_r($matches[0]);

# [0] => Array
#    (
#        [0] => word1
#        [1] => word-2
#        [2] => word.3
#        [3] => word*4
#    )
+1
source

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


All Articles