Rick
Rick

Reputation: 13

How to extract multiple values from a string to call an array?

I want to extract values from a string to call an array for basic template functionality:

$string = '... #these.are.words-I_want.to.extract# ...';

$output = preg_replace_callback('~\#([\w-]+)(\.([\w-]+))*\#~', function($matches) {
    print_r($matches);
    // Replace matches with array value: $these['are']['words-I_want']['to']['extract']
}, $string);

This gives me:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => .extract
    [3] => extract
)

But I'd like:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => are
    [3] => words-I_want
    [4] => to
    [5] => extract
)

Which changes do I need to make to my regex?

Upvotes: 1

Views: 250

Answers (2)

anubhava
anubhava

Reputation: 785058

You can use array_merge() function to merge the two resulting arrays:

$string = '... #these.are.words-I_want.to.extract# ...';
$result = array();

if (preg_match('~#([^#]+)#~', $string, $m)) {
   $result[] = $m[0];
   $result = array_merge($result, explode('.', $m[1]));
}

print_r($result);

###Output:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => are
    [3] => words-I_want
    [4] => to
    [5] => extract
)

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173552

It seems that the words are simply dot separated, so match sequences of what you don't want:

preg_replace_callback('/[^#.]+/', function($match) {
    // ...
}, $str);

Should give the expected results.

However, if the # characters are the boundary of where the matching should take place, you would need a separate match and then use a simple explode() inside:

preg_replace_callback('/#(.*?)#/', function($match) {
    $parts = explode('.', $match[1]);
    // ...
}, $str);

Upvotes: 3

Related Questions