Olirav
Olirav

Reputation: 165

Regex replace to reorder text

I have a page which needs to output text from a DB, this text will sometimes have one or more videos embeded via iframe. I need to output this so the videos are displayed down the left of the text (Via css floating) - although this requires the video to be placed before the text.

At the moment I have this

$text = preg_replace("#(.*?)(<iframe.*?</iframe>)(.*?)#i", '$2 $1 $3', $text);

However this will only move the first iframe if more than one is present, leaving the others where they were.

Example In:

abcdefghijkl
<iframe....></iframe>
mnopqrstuvwxyz
<iframe....></iframe>

Desired Out:

<iframe....></iframe>
<iframe....></iframe>
abcdefghijklmnopqrstuvwxyz

Upvotes: 1

Views: 127

Answers (1)

Desolator
Desolator

Reputation: 22759

well you can use preg_replace_callback to do such thing here's an example but you will be using globals which is really a dirty solution:

$str = 'abcdefghijkl
<iframe....></iframe>
mnopqrstuvwxyz
<iframe....></iframe>';

global $myText;
global $myIframe;

preg_replace_callback("/([^<]+)(<iframe[^>]+>[^<]*<\/iframe>)/i",
            function($matches) use ($myText) {
                    global $myText, $myIframe;
                    $myText .= $matches[1];
                    $myIframe .= $matches[2]; 

            },
            $str);

echo $myIframe."<br>".$myText;

Upvotes: 1

Related Questions