2

I have an expression [text][id] which should be replaced with a link <a href='id'>text</a>

The solution is (id is integer)

$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);

However, in some cases (not always!) the expression may be as the following

[text][id][type]

which should in this case be replaced with <a href='id' class='type'>text</a>

Ideas?

4
  • There are no numbers in your example what is \[([0-9]+)\] doing? or id is an integer? Commented Jun 11, 2017 at 21:53
  • Yes, ID is integer Commented Jun 11, 2017 at 21:55
  • What are text and type? I think you are going to need 2 regex for this because the replacement is going to need have class="$3" everytime, or I guess you could strip it in another step, if empty. Commented Jun 11, 2017 at 21:57
  • 2
    See ideone.com/PKydSV Commented Jun 11, 2017 at 22:03

1 Answer 1

5

The solution using preg_replace_callback function:

$str = 'some text [hello][1] some text [there][2][news]';  // exemplary string

$result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){
    $cls = (isset($m[3]))? " class='{$m[3]}'" : "";  // considering `class` attribute
    return "<a href='{$m[2]}'$cls>{$m[1]}</a>";
},$str);

print_r($result);

The output (as web page source code):

some text <a href='1'>hello</a> some text <a href='2' class='news'>there</a>

  • (?:\[([^][]+)\])? - considering optional 3rd captured group (for class attribute value)
Sign up to request clarification or add additional context in comments.

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.