a .akan
a .akan

Reputation: 1

Capturing content between square bracket tags in PHP

I want to put content from bracket defined tags in text below and put all of them into an array, My attempts in PHP and preg_match function has been failed many times. What should I do in PHP using preg_match function?

$string="[restab title="name"]John O'Brian[/restab][restab title="telephone"]+15254636544[/restab][restab title="address"]Newyork, Wallstreet Ave, No 5[/restab]"

Upvotes: 0

Views: 1111

Answers (3)

Kim Peeters
Kim Peeters

Reputation: 11

You could look at this library how it's done or just use/alter it.

https://github.com/jbowens/jBBCode

Edit: If you only need the tags starting with restab. Perhapse this will suffice:

$text = '[restab title="name"]John O\'Brian[/restab][restab title="telephone"]+15254636544[/restab][restab title="address"]Newyork, Wallstreet Ave, No 5[/restab]';

preg_match_all("#\[restab title=\"(.+?)\"](.*?)\[/restab\]#",$text,$matches);

This will give every tag starting with [restab title="..."]

Upvotes: 1

Aleksander Wons
Aleksander Wons

Reputation: 3967

You might be looking for something like this:

preg_match_all('/\[[^]]+\]([^[]+)\[\/[^]]+\]/is', $string, $matches);

This gives you the following results:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(42) "[restab title="name"]John O'Brian[/restab]"
    [1]=>
    string(47) "[restab title="telephone"]+15254636544[/restab]"
    [2]=>
    string(62) "[restab title="address"]Newyork, Wallstreet Ave, No 5[/restab]"
  }
  [1]=>
  array(3) {
    [0]=>
    string(12) "John O'Brian"
    [1]=>
    string(12) "+15254636544"
    [2]=>
    string(29) "Newyork, Wallstreet Ave, No 5"
  }
}

You can add more brackets to capture text within square brackets.

Upvotes: 1

online Thomas
online Thomas

Reputation: 9381

preg_match_all("/\[[^\]]*\]/", $text, $matches);

The regex captures everything in the $text between [ and ]. You need preg_match_all() if you want to match everything and not just the first instance

Upvotes: 0

Related Questions