Simon Andersson
Simon Andersson

Reputation: 375

preg_replace with attribute values

Im using preg_replace to decode bbcode and i use (.*?) to get the attribute values.

I want to replace it with font-size:\10px; (font-size:(.*?)0px;) so that for example if the attribute value is 7 then the font size would be 70. but instead it thinks that i want the value \10. What can i do to separate the attribute value and the 0?

Is it possible to do like 'font-size:'.\1.'0px;' or something similar to separate the attribute value from the zero?

Upvotes: 0

Views: 546

Answers (3)

mpyw
mpyw

Reputation: 5754

Apply to this text:

$str = <<< EOD
[size="4"]test1[/size]
[size="4]test2[/size]
[size=4"]test3[/size]
[size=4]test4[/size]
EOD;
$pattern = '@\\[size=("?)(\\d++)\\1\\](.*?)\\[/size\\]@s';

preg_replace:

$replace = '<span style="font-size:${2}0px;">$3</span>';    
echo preg_replace($pattern,$replace,$str);

preg_replace_callback:

$replace = function ($matches) {
    return sprintf('<span style="font-size:%s0px;">%s</span>',
        $matches[2],
        $matches[3]
    );
};     
echo preg_replace_callback($pattern,$replace,$str);

Result:

<span style="font-size:40px;">test1</span>
[size="4]test2[/size]
[size=4"]test3[/size]
<span style="font-size:40px;">test4</span>

Upvotes: 1

mpyw
mpyw

Reputation: 5754

Omg... PHP manual makes a big confusion...

About this code:

echo preg_replace('/^(1)(2)(3)(4)(5)$/', $r, '12345');

Expected output:

12345!!12345!!

When using heredoc:

$r = <<< EOD
$0!!\${1}2\${3}4$5!!
EOD;

However, not using heredoc:

$r = '$0!!${1}2${3}4$5!!';

Yes, backslashes are unneeded.

Upvotes: 0

Matteo B.
Matteo B.

Reputation: 4074

\${1}0 is the solution as documented here.

[edit]

I tried all possible amounts of backslashes and have to say.. to me it makes absolutely no sense, that

echo preg_replace('/(2.)/', '\\${1}', '12345');

outputs 1${1}45

But I have found one solution, heredoc:

$a = <<<ABC
\${1}
ABC;
echo preg_replace('/(2.)/', $a, '12345');

Upvotes: 4

Related Questions