replace line break with 2 spans in php

Go To StackoverFlow.com

1

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>
2012-04-04 08:21
by Yens
The CSS spec teaches you to not create meta-representation with class attributes and div/spans. So please don't do it. The answer is: DOMDocument + Xpath - hakre 2012-04-04 08:24
what about divs? why do you not use div instead of span? div is a block element which should work for you like a charm - Lukas Schulze 2012-04-04 08:30
div is not a valid element inside a - PatrikAkerstrand 2012-04-04 09:00


1

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);
2012-04-04 08:33
by Alix Axel


1

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.

2012-04-04 08:29
by hakre
I'll try this changing the spans into div's considering semantics. I'm not sure about the formatting because our client uses tinymce to insert the text into the database - Yens 2012-04-04 08:34
Ads