1

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?

1
  • Seems like an explode('.', $yourvar) is what you need. Commented Jun 29, 2014 at 12:36

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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
)

3 Comments

Hey there anu, nearly identical answer, deleting mine and +1 to you :) Off to sleep catch you tomorrow.
Sorry just came back online, missed identical answer part otherwise I would have avoided answering it.
No, you're absolutely fine, my original answer didn't have the demo, and when you started on your answer I must have been in IDEONE trying to make mine work. We probably got there around the same time, and you got there in a shorter amount of time, so kudos to you. :) After I posted, I saw that yours was similar and had a small bug but you fixed it. My answer doesn't add anything, hope yours gets some upvotes. Sorry, too chatty, powering down the computer see you tomorrow.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.