RussellHarrower
RussellHarrower

Reputation: 6810

PHP - strpos if it contains anything inside [ ]

I have the following which works great, but now what I want to do is if a user types [MAP] then I want to get the word MAP

I also want allow users to send things like [MAP = array("LOCATION"=>"Melbourne Australia")]

and for the PHP to make map a array so I can then send it to a function later on

I currently do the following

$map = strpos($stringtocheck, "[MAP]");

But the issue here, is if we have a number of [] with different insides like [BOLD], [INSERT] etc then it wont find it and put it in its own $ and also it means we need to know what the array is field with or anything like that

Upvotes: 0

Views: 469

Answers (1)

Petah
Petah

Reputation: 46050

A simple regex will pull info out of square brackets:

$s = 'Yo be [diggin] [my leet] scriptzors!';
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
var_dump($matches[1]);

Result:

array(2) {
  [0]=>
  string(6) "diggin"
  [1]=>
  string(7) "my leet"
}

Example: http://codepad.viper-7.com/erBpuB

Upvotes: 2

Related Questions