Sebastian Jeliazkov Sebastian Jeliazkov - 1 year ago 33
PHP Question

Adding letter to every word in variable(string)

I got variable

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

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 />

Answer Source

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

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

PHP Demo:
Regex Demo:

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);