Andelas
Andelas

Reputation: 2052

preg_match bbcode

I currently have bbcode like this

[caption=Some text goes here]image.jpg[/caption]

I'd like to use php's preg_match so I can get the value of the image.jpg, regardless of what's next to 'caption='. Can someone help me out?

Upvotes: 0

Views: 2387

Answers (4)

Madara's Ghost
Madara's Ghost

Reputation: 174977

RegExp is not magic. PHP already has a pre-made extension library to handle BBCode.

Don't reinvent the wheel, and don't make it hard on yourself.

Upvotes: -1

Martijn
Martijn

Reputation: 73

If you want to match the complete bbcode tag, including the caption, use

preg_match("/\[caption=(.+)\](.+)\[\/caption\]/", $myString, $matches);

This will result in the following $matches array:

Array
(
    [0] => [caption=Some text goes here]image.jpg[/caption]
    [1] => Some text goes here
    [2] => image.jpg
)

Upvotes: 0

anubhava
anubhava

Reputation: 785256

You can use this regex:

$str = '[caption=Some text goes here]image.jpg[/caption]';
if (preg_match('/^\[[^\]]+]([^[]+)/', $str, $arr))
   echo "image: $arr[1]\n";

OUTPUT

image: image.jpg

Upvotes: 1

agent-j
agent-j

Reputation: 27923

Raw regex:

]([^\]]+)[/caption]

preg_match("]([^\]]+)[/caption]", myString, $matches)

image.jpg would be in the first group. $matches[1] (I'm not certain I escaped it correctly in php).

Upvotes: 1

Related Questions