0

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.

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

5 Comments

what are you returning from?
@sgroves The function in the question.
I like this way, but strrpos returns false hard... (php 5.4.11)
I had the arguments to strrpos() backwards (most PHP functions have the needle before the haystack). Fixed it, now it works.
Changed to strripos() to be case-insensitive.
2

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

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

regexp

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.