tags:

views:

177

answers:

3

i have a string with double quote like this

$count = 5;
$str = "result: $count";
echo $str; //result: 5

variable parsing work well, and my problem is $count var must be define later than $str

$str = "result: $count";
$count = 5;
echo $str; //result:

So i will use single quote and ask a question here to finding a way to parse var whenever i want

$str = 'result: $count';
$count = 5;
//TODO: parse var process
echo $str; //result: 5

I'm will not using regex replace.

A: 

preg_replace is the simplest method. Something like this:

$str = preg_replace("/\\$([a-z0-9_]+)/ie", "$\\1", $str);

But if you really don't want to use a regex, then you'll have to parse the string manually, extract the variable name, and replace it.

Jon Benedicto
A: 

Why don't you use a function?

function result_str($count) { return "result: $count"; }
Imran
+7  A: 

For this type of thing, I'd probably use string formatting. In PHP, that'd be printf.


?php
$str="result: %d"
....dostuff.....define $count.....
printf($str,$count)
?

edit: although, the best way to do this probably depends partly on why you have to define $string before $count.

If it's a string that's repeated a lot, and you wanted to put it in a global variable or something, printf would be my choice, or putting it in a function as other answers have suggested.

If the string is only used once or twice, are you sure you can't refactor the code to make $count be defined before $string?

finally, a bit of bland theory: when you write '$string = "result: $count"', PHP immediately takes the value of $count and puts it into the string. after that, it isn't worried about $count anymore, for purposes of $string, and even if $count changes, $string won't, because it contains a literal copy of the value. There isn't, as far as I'm aware, a way of binding a position in a string to a yet-to-be-defined variable. The 'printf' method leaves placeholders in the string, which the function printf replaces with values when you decide what should go in the placeholders.

So, if you wanted to only write $string = "result: $count" $count=5 $echo string

(and not have to call another function)

and get "result: 5", there's no way to do that. The closest method would be using placeholders and printf, but that requires an explicit call to a function, not an implicit substitution.

YenTheFirst
ALso if you wan't to format the string, but not immidiatly output it, use sprintf() instead of printf().
Pim Jager
Right. For some reason, I don't know, I talked about printf but linked to sprintf. Maybe it was because I wrote the answer at 11 pm last night. :)
YenTheFirst