How can I prepend a string, say 'a'
stored in the variable $x
to each line of a multi-line string variable using PHP?
There are many ways to achieve this.
One would be:
$multi_line_var = $x.str_replace("\n", "\n".$x, $multi_line_var);
Another would be:
$multi_line_var = explode("\n", $multi_line_var);
foreach($multi_line_var AS &$single_line_var) {
$single_line_var = $x.$single_line_var;
}
$multi_line_var = implode("\n", $multi_line_var);
Or as a deceitfully simple onliner:
$multi_line_var = $x.implode("\n".$x, explode("\n", $multi_line_var));
The second one is dreadfully wasteful compared to the first. It allocates memory for an array of strings. It runs over each array item and modifies it. And the glues the pieces back together.
But it can be useful if one concatenation is not the only alteration you're doing to those lines of text.
Can also use:
echo preg_replace('/^/m', $prefix, $string);
The /
are delimiters. The ^
matches the beginning of a string. the m
makes it multiline.
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With