简体   繁体   English

用正则表达式替换所有匹配项(第一个表达式除外)

[英]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. 我不确定仅使用preg_replace函数是否可行,但是我只想获取第一个图像,而忽略其他所有图像。

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. 似乎仅使用limit属性是不够的,因为我不想跳过第一个图像并保留其余图像。 I need the opposite: Keep the 1st image and replace all the others. 我需要相反的情况:保留第一个图像并替换所有其他图像。

You can use preg_replace_callback to accomplish that. 您可以使用preg_replace_callback完成此操作。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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