Yens
Yens

Reputation: 925

replace line break with 2 spans in php

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>

Upvotes: 1

Views: 620

Answers (2)

Alix Axel
Alix Axel

Reputation: 154553

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

Upvotes: 1

hakre
hakre

Reputation: 197777

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.

Upvotes: 1

Related Questions