otinanai
otinanai

Reputation: 4025

Replace all matches for a regular expression except for the first one

I'm not sure if this is possible only with preg_replace function but I would like to get only the first image and ignore all the other.

This code excludes all images in the text I want to display, but I need to get only the first image.

if (!$params->get('image')) {
    $item->introtext = preg_replace('/<img[^>]*>/', '', $item->introtext);
}

Can you please point me to the right direction to achieve this?


EDIT :

It seems that using the limit property is not enough since I don't want to skip the 1st image and keep the remaining. I need the opposite: Keep the 1st image and replace all the others.

Upvotes: 0

Views: 275

Answers (1)

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

You can use preg_replace_callback to accomplish that. This function will execute a callback function you pass as parameter that will return a replacement string for every match it founds in your original string.

In this case, we will return the own match in the first occurrence so it will not be replaced.

$i = 0;
$item->introtext = preg_replace_callback('/<img[^>]*>/', function($match) use (&$i) {
    if ($i++ == 0) // compares $i to 0 and then increment it
        return $match[0]; // if $i is equal to 0, return the own match

    return ''; // otherwise, return an empty string to replace your match
}, $item->introtext);

Upvotes: 3

Related Questions