Dylan Moffett
Dylan Moffett

Reputation: 43

Regex - Get all characters after each instance of specific character

I am very new to regex and just cannot figure out how to write a pattern to match what I need. Any help would be awesome!

I want to use PHP & regex to capture each set of characters in a string that follow a specific unique character (delimiter), plus any set of characters that precedes the first instance of that delimiter. I then want to "match" the desired output into a PHP array.

I've looked through the following responses, and while they are close, they don't quite help me achieve what I need:

This is the PHP function I'm currently working with, but it currently only finds the characters between the delimiter:

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

NOTE: the number of items in a given string may vary, so I can't use a pattern that expects a specific number of delimiters (ex. /^(.*?)>(.*?)>(.*?)>$/)

Upvotes: 4

Views: 2106

Answers (3)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can simply use array_map along with explode as

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

Output:

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

You can Check it here

Upvotes: 4

chris85
chris85

Reputation: 23892

I would use preg_split, http://php.net/preg_split, for this.

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

Output:

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

The \s* means any number of whitespace characters.

This is similar to using an explode.

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

but as you see with the explode you have the whitespaces:

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

Upvotes: 1

Martin Konecny
Martin Konecny

Reputation: 59571

As mentioned, you could just use explode for this:

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

However for completeness sake, let's also use RegEx.

In this case, we can tell the Regular Expression to group all characters together that aren't whitespace and aren't the delimiter >:

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

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

Upvotes: 1

Related Questions