简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM