afarazit
afarazit

Reputation: 4984

Regular expression to capture string between square brackets

I have an array that its first element might contains something like [some text, here. That's some text] I'm trying to figure out a pattern to check if such string exists and if not create it but having problem with making the pattern. Here's what I've done so far

$pattern = '/^\[*\]$/';
if(preg_match($pattern,$exploded[0])){
    $name = array_shift($exploded);
}else{
    $name = "[Unnamed import] - " .gmdate("His");
}

But I always get [Unnamed import] - 032758 even when I'm sure that pattern match

Upvotes: 2

Views: 176

Answers (3)

codaddict
codaddict

Reputation: 455000

You are checking to see if a string begins with [ and ends with a ]. You can easily do it without regex too as:

if(strlen($str) && $str[0] == '[' && $str[strlen($str)-1] == ']') {
        // pattern found.
}

Upvotes: 1

codaddict
codaddict

Reputation: 455000

The regex ^\[*\]$ is incorrect.

^   - Start anchor
\[  - A literal [
*   - Quantifier for zero or more
\]  - A literal ]
$   - End anchor

The quantifier * applies to the part before it, in this case it applies to [. I guess you've confused the * with its usage in shell where it means any characters any number of times.

So your regex matches zero or more of [ at the beginning of the string and one ] at the end of the string.

The equivalent of shell's * in regex is .* which matchs any character (except newline) any number of times. So you can try the regex ^\[.*\]$

Alternatively you can try: ^\[[^\]]*\]$

Upvotes: 3

mario
mario

Reputation: 145482

The * by itself doesn't represent multiple characters. You need dot (=any char) followed by the asterisk .*, else the asterisk means to match zero or more [ chars - because it always quantifies the preceeding character.

Upvotes: 1

Related Questions