php - RegEx with optional part inside

475

I'm pretty new to regular expression. Just tried to analyse a "BB-Code" that could do something like this:


Pattern:

\[element title=(.*)picture=(\d+)](.*)(?:\[caption](.*):?\[/caption])?\[/caption].*

Search:

[element title=element title picture=32]Lorem ipsum dolor[caption]Photo by John Doe[/caption][/element]

[element title=element title picture=32]Lorem ipsum dolor[/element]


Well, the caption-part should be optional and both entries should give results. How can I reach this?

52

Answer

Solution:

How about this:

\[element title=(.*)picture=(\d+)\](.*?)(\[caption\](.*)\[/caption\])?\[/element\]

It will match both:

[element title=element title picture=32]Lorem ipsum dolor[caption]Photo by John Doe[/caption][/element]

[element title=element title picture=32]Lorem ipsum dolor[/element]

Example

in PHP, you can use it this way:

$regex = '#\[element title=(.*)picture=(\d+)\](.*?)(\[caption\](.*)\[/caption\])?\[/element\]#i';
$text = '[element title=element title picture=32]Lorem ipsum dolor[caption]Photo by John Doe[/caption][/element]';    

preg_match ( $regex, $text, $match );

print_r( $match );

The array$match will have several elements. Those are the strings that are surrounded by round-brackets( and) in the regular expression. One of them is the caption text.

Program execution and output can be seen here .

Write your answer




109
votes

Answer

Solution:

\[element title=(.*) picture=[0-9]+\](.*)(\[caption\](.)*\[\caption\])?\[/element\]

People are also looking for solutions to the problem: php - One huge XML file with long SQL statement or not?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.