Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend each line of a variable with a string

Tags:

php

How can I prepend a string, say 'a' stored in the variable $x to each line of a multi-line string variable using PHP?

like image 453
Max Hudson Avatar asked Nov 28 '22 09:11

Max Hudson


2 Answers

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.

like image 45
Mihai Stancu Avatar answered Dec 15 '22 10:12

Mihai Stancu


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

like image 134
Gordon Avatar answered Dec 15 '22 11:12

Gordon