0

I have a template string like this

$myStr ="<font face=\"#3#\" size=\"6\">TEST STRING</font>";

And an array of fonts like this

$fontList = array(
    0 => "ubuntumono",
    1 => "opensans",
    2 => "opensanscondensed",
    3 => 'opensanslight',
    4 => 'exo2',
    5 => 'exo2light'
);

Now I want to check my string for face=\"#3#\" (3 is the index of font in $fontList)

and replace it with face=\"opensanslight\"

How can I do it with Regex & PHP? Thank you.

1 Answer 1

3

Assuming PHP 5.3.0 or better:

$myStr = preg_replace_callback('/#(\d+)#/', function ($matches) use ($fontList) {
    return $fontList[$matches[1]];
}, $myStr);

Example

If you want to only change #number# when it is surrounded by quotes:

$myStr = preg_replace_callback('/"#(\d+)#"/', function ($matches) use ($fontList) {
    return '"' . $fontList[$matches[1]] . '"';
}, $myStr);

Example

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

6 Comments

the index in $matches should be zero? if i'm not wrong
No. $matches[0] would be #3#. $matches[1] would be 3.
ohh ok. nice answer (Y)
Thank you @Sean Bright for your rapid reply but I want to ask something more. I guess this solution will also change other parts of the string Ex: <font face=\"#3#\" size=\"6\">TEST #114# another occurence</font>.How can I solve this problem. By the way $fontList array may have more than 100 fonts. Thank you.
@user3253797: I made an edit that will make it only match when surrounded by quotes. Does that satisfy your needs?
|

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.