![](/img/trans.png)
[英]How to replace all occurrences of a character except the first one in PHP using a regular expression?
[英]Replace all matches for a regular expression except for the first one
我不确定仅使用preg_replace
函数是否可行,但是我只想获取第一个图像,而忽略其他所有图像。
此代码排除了我要显示的文本中的所有图像,但是我只需要获取第一张图像。
if (!$params->get('image')) {
$item->introtext = preg_replace('/<img[^>]*>/', '', $item->introtext);
}
您能指出我正确的方向吗?
编辑:
似乎仅使用limit
属性是不够的,因为我不想跳过第一个图像并保留其余图像。 我需要相反的情况:保留第一个图像并替换所有其他图像。
您可以使用preg_replace_callback完成此操作。 此函数将执行您作为参数传递的回调函数,该函数将为在原始字符串中找到的每个匹配项返回一个替换字符串。
在这种情况下,我们将在第一次出现时返回自己的匹配项,因此不会被替换。
$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.