Consider the following HTML string:
<p>This is line 1 <br /> and this is line 2</p>
How can i replace the above with the following string using PHP / Regex
<p><span class="single-line">This is line 1</span><span class="single-line">and this is line 2</span></p>
This works but I would advise you not to rely on regular expressions for HTML parsing / transformation:
$string = '<p>This is line 1 <br /> and this is line 2</p>';
$pattern = '~([^<>]+)<br[[:blank:]]*/?>([^<>]+)~i';
$replacement = '<span class="single-line">$1</span><span class="single-line">$2</span>';
echo preg_replace($pattern, $replacement, $string);
I do not really suggest that you actually do it (because IMHO you're misusing markup and classes), however it's actually pretty simple:
you replace
<p>
with
<p><span class="single-line">
and
<br />
with
</span><span class="single-line">
and finally
</p>
with
</span></p>
A PHP function that can replace strings is strtrDocs.
Note that this works only for exactly the HTML fragment you've given in your question. If you need this more precise, you should consider using DOMDocument and DOMXPath as I already commented above.