Sebastian Jeliazkov Sebastian Jeliazkov - 3 months ago 8
PHP Question

Adding letter to every word in variable(string)

I got variable

$test = "test1<br />
test2<br />
test3";


I want to add before every word in the string a Letter.Also the string contains break tags as i post it.

Want to look like:

$test = "Ptest1<br />
Ptest2<br />
Ptest3";

Answer

You can use a regex to loop through the string and add your value.

$arr = "test1<br />
         test2<br />
         test3";
echo preg_replace('/^(\h*)([A-Za-z])/m','$1P$2',$arr);

PHP Demo: https://eval.in/630398
Regex Demo: https://regex101.com/r/xV9nY0/1

The /s are delimiters telling where the regex starts and ends.
The m modifier makes the ^ match at the start of each line.
The \h* is any amount of whitespace before an alpha character (you can add to that character class if other characters should also be allowed).

To allow the line to start with numbers as well try:

echo preg_replace('/^(\h*)([A-Za-z\d])/m','$1P$2',$arr);