0

I want to replace fields values that I get from a database query as an array of objects in a string like this:

"My name is {name} and I live in {city}."

I found the following solution but only works when I replace the values with normal strings, not with an object property:

preg_replace('/\{([a-z]+)\}/', "$row->\\1", $myString)

I get this error: Object of class stdClass could not be converted to string.

Why it can't evaluate $row->fielname?

Best regards.

0

1 Answer 1

2

You asked

Why it can't evaluate $row->fielname?

for the following line of code:

preg_replace('/\{([a-z]+)\}/', "$row->\\1", $myString)

To better understand that, take a look at the string in question:

"$row->\\1"

Taking the rules of PHP double quoted string variable substitution into account, it will result in the following before the function is called:

***contents of the variable $row as string*** . '->\1'

If $row can not be converted to string (which can happen with objects), this will create a fatal error.

If $row contains the number 42 it will be this:

preg_replace('/\{([a-z]+)\}/', '42->\\1', $myString)

Hope this example is useful.

What you probably want to do is the following:

preg_replace_callback('/\{([a-z]+)\}/', function($groups) use ($row) {
    return $row->{$groups[1]};
}, $myString);
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I haven't noticed on this, PHP evaluates the string before the function is called. Thank you very much.
Yes PHP needs to evaluate that before calling the function, because only parameters - not expressions - are passed to a function. That is the same in nearly any computer language I know. So you can say this is common and nothing PHP specific. Just FYI. So in case you do some javascript or so, it's the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.