1

I am using preg_replace_callback, Here is what i am trying to do:

$result = '[code]some code here[/code]';

$result = preg_replace_callback('/\[code\](.*)\[\/code\]/is', function($matches){
      return '<div>'.trim($matches[1]).'</div>';
}, $result);

The idea is to replace every match of [code] with <div> and [/code] with </div>, And trim the code between them.

The problem is with this string for example:

$result = '[code]some code[/code]some text[code]some code[/code]';

What i want the result to have 2 separated div's:

$result = '<div>some code</div>some text<div>some code</div>';

The result i get is:

$result = '<div>some code[code]some text[/code]some code</div>';

Now i know the reason, And i understand the regex but i couldn't come up with solution, If anyone know how to make it work i will be very thankful, Thank you all and have a nice day.

1
  • 2
    Try a non-greedy regex: /\[code\](.*?)\[\/code\]/is. Commented Oct 18, 2013 at 19:02

2 Answers 2

3

Your problem is greedy matchiing:

/\[code\](.*?)\[\/code\]/is

Should behave as you want it to.

Regex Repetition is greedy, which means it captures as many matching items as it can, then gives up one match at a time if it finds that it can't match what's left after the repetition. By using a question mark, you indicate that you want to match non-greedily, or lazily, meaning that the engine will try to match the rest of the regular expression FIRST, then grow the size of the repetition after.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm glad, make sure you hit "accept" so others know at first glance what worked for you.
In about 6min, Thanks again.
2

You don't need to use preg_replace_callback() since you can extract the "trimed" content:

$pattern = '~\[code]\s*+((?>[^[\s]++|\s*+(?!\[/code])\[?+)*+)\s*+\[/code]~i';
$replacement = '<div>$1</div>';
$result = preg_replace($pattern, $replacement, $result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.