0

I'm trying construct preg_match_all to search for all the values found in a string that begins with [$_ and ends with _$], and store the found values in an array.

So, in the following example:

$str = "I have a [$_dog_$], a [$_cat_$], but not a ferret.";
preg_match_all($regex_pattern, $str, $normalPets);

$normalPets should contain [$_dog_$] and [$_cat_$].

What is the $regex_pattern for this?

Thanks

3
  • Thanks for the good example and explanation. But. What have you tried? Commented Oct 2, 2012 at 19:56
  • preg_match_all("/^[\$__\$]$/", $str, $normalPets); Commented Oct 2, 2012 at 19:58
  • Please note when I posted this it removed the underscore before dog and after dog. It should be [$_dog_$] Commented Oct 2, 2012 at 19:59

1 Answer 1

2

Should be:

$regex_pattern = '/\[\$_.+_\$\]/U';
Sign up to request clarification or add additional context in comments.

5 Comments

there is no need for the capturing group
also you should include the underscores
added the underscores and removed capturing group
Thanks. You are a regex genius, although it's storing [$_dog_$] and [$_cat_$] twice. I can deal with that with an array function but is there something in the regex pattern that is causing the found values to be stored 2x?
The reason for this is the way how the result is stored in $normalPets. The first entry is for the whole match and all the following entries (in you case only one) for all sub patterns. Unless you use the PREG_SET_ORDER constant as the fourth parameter $normalPets[0] should contain your result.

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.