ZloyPotroh
ZloyPotroh

Reputation: 377

php regexp last match

Condition: I have a peace of html code from wysiwig (Brief). I need to inject readmore link to the last paragrpaph (p-tag)

public function injectReadMore($html){
        if( $this->is_html($html) ){
            return preg_replace('#\<\/p\>$#isU',' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a>$0', $html);
        } else {
            return '<p>'.$html.' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a></p>';
        }
    }

Yep. What i wrote it's not right. Cuz if

$html = '<p>sdfgsdfg</p><div><p>sdfgsdfg</p> </div> ';

Fail.

Tried regexp's:

'#\<\/p\>[^p]+?$#isU'
'#\<\/p\>[^\/p]+?$#isU'
'#\<\/p\>[^[\/p]]+?$#isU'

and the same variants of RegExp. I don't understand something, maybe all;)

Help pls. Thanks, Brothers.

Upvotes: 0

Views: 161

Answers (3)

Barmar
Barmar

Reputation: 782130

This is easy to do with regular string replacement instead of regexp:

$pos = strripos($html, '</p>'); // Find last paragraph end
if ($pos !== false) { // Use exact matching, to distinguish 0 from false
    // Insert anchor before it
    $html = substr_replace($html, ' <a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a>', $pos, 0);
}
return $html;

Upvotes: 2

cmorrissey
cmorrissey

Reputation: 8583

Negative lookahead but remember to escape your html.

preg_replace('/\<\/p\>(?!.*\<\/p\>)/isU', '<a href="javascript:void(0)" class="toggle-full-dsc">Читать полностью</a></p>', $html);

Upvotes: 1

Valery Viktorovsky
Valery Viktorovsky

Reputation: 6736

You can use regex pattern with negative lookahead (?!…)

</p>(?!.*</p>)

regexp

Example: http://www.debuggex.com/r/rgV-ddCbL-BH_rL_/0

Upvotes: 2

Related Questions