If I have a string, and I search in the string for a particular text after a signal, is there any way to output the text string with the particular text after the signal replaced with a variable of the same name?
Example
I have
$strin="This is #fruit"
$fruit="omg"
So I search $strin, extract “fruit” using regex, then replace #fruit with the value of $fruit.
Any ideas how to do this in PHP?
Edit – It may not always be fruit. There is basically a set of #things and $variablesofthethings. So it will not always be fruit. But every #things will have a $variablesofthings. So, I don’t know what the thing will be but I know there is a variable for it with the same name. hope this makes sense!
You could use variable variables in PHP to have your value, and then use PHP built-int string interpolation to place the value of the variable in the string.
this way your variable names could be dynamic too.
Variable Variables:
in PHP you could have a variable like this:
But you could have a variable, whose name is detected from another variable. like this:
This references to the variable whose name is the value of the variable $name. So for example if you receive the value of variable $name from the CLI arguments:
Then if the user enters ‘fruit’ in the command line, your variable $name would have the value of ‘fruit’, and then $$name would refer to the variable named $fruit with the value of ‘apple’.
now you could use PHP interpolation (in strings enclosed by double quotes) to replace the variable, with its value:
Here is completed example of how to do this: