Tarlan Mamedzadeh
Tarlan Mamedzadeh

Reputation: 93

PHP preg_replace modification

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?

Upvotes: 2

Views: 223

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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)

Upvotes: 5

Related Questions