Jump to content

What preg_match_all regex would I use?


jamesxg1

Recommended Posts

'/{([^}]+)}/'

 

Maybe. I am not super good at it, but that should cover some of the cases. The tricky thing about regexes is that they are tricky to cover corner cases...what if...?

 

Spot on mate, cheers.

 

Many thanks,

 

James.

Another option

'/{(.*?)}/'

 

Thats what I had wrote originally but I thought it might be unstable, is this the case?

 

. means any character

* means zero or more of the preceding character

? means zero or one of the preceding character

(character could be a set of characters, or whatever, a unit e.g. (blah)*, a*, [a-s]*...)

 

So what is zero or one of zero or more of any character? I don't think it makes sense, but I could be missing something, that's why I asked if he knows what it really means.

 

The problem with '{.*}' would be that .* can be a }, which is not what you want. You want to match opening brace, anything other than a closing brace, then a closing brace, so '{[^}]*}'.

The question mark makes the match "non greedy".

 

If you leave the '?' off the expression and there are two words within braces you would get everything from the start of the first word to the end of the last word (as dabaR stated). The ? modifier corrects this by making the match non greedy

 

Regular Expression Tutorial Part 5: Greedy and Non-Greedy Quantification

 

Example:

$string = "This {is a} string {of} text.";

//Without the non-greedy modifier
preg_match_all('/{(.*)}/', $input, $matches);
print_r($matches);

//Ouput: 
//Array
//(
//    [0] => Array
//        (
//            [0] => {is a} string {of}
//        )
//    [1] => Array
//        (
//            [0] => is a} string {of
//        )
//)
  
//With the non greedy modifier
preg_match_all('/{(.*?)}/', $input, $matches);
print_r($matches);

//Output:
//Array
//(
//    [0] => Array
//        (
//            [0] => {is a}
//            [1] => {of}
//        )
//    [1] => Array
//        (
//            [0] => is a
//            [1] => of
//        )
//)

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.