Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the substr() function inside preg_replace() function?

This is what I have so far, but whatever I try, my album-content won't get truncated with substr().

$gallery = preg_replace('/(<div class="album-content">)(.*?)(<\/div>)/e', "'$1' . substr(\"$2\", 0, 50) . '$3'", $gallery);

UPDATE:

Turns out my class name was incorrect, and my regex does seem to work. I only had to do another str_replace() to un-escape the output.

$gallery = preg_replace('/(<div class="album-desc">)(.*?)(<\/div>)/e', "'$1' . substr(\"$2\", 0, 50) . '$3'", $gallery);
$gallery = str_replace('\"album-desc\"', '"album-desc"', $gallery);

Output before modifying:

<a href="..." class="album">
    <div class="album-content"><p class="album-title">Album 1</p>
        <div class="album-desc"><p>This will be truncated by substr().</p></div>
    </div>
    <img src="..." />
</a>

Thanks all, anyways!

like image 890
fishbaitfood Avatar asked Jan 14 '13 19:01

fishbaitfood


1 Answers

Use preg_replace_callback()

$replace = preg_replace_callback('/(asd)f/i', function($matches) {
    $matches[1] = substr($matches[1], 0, 2);

    return $matches[1];
}, 'asdf');

Full documentation

like image 96
David Harris Avatar answered Oct 13 '22 01:10

David Harris