Image 提取第一个图像并从字符串中删除第一个图像

Image 提取第一个图像并从字符串中删除第一个图像,image,Image,我有一个同时包含文本和图像的字符串,但我只想使用php删除第一个图像 $string = 'This is my test <img src="link_to_image1">, some other text. <img src="link_to_another_image" border="0">'; $str = preg_replace('/\<img src=\"[aA-zZ0-9\/\_\.]+\"\>/','',$string, 1); 使用回

我有一个同时包含文本和图像的字符串,但我只想使用php删除第一个图像

$string = 'This is my test <img src="link_to_image1">, some other text.
<img src="link_to_another_image" border="0">';
$str = preg_replace('/\<img src=\"[aA-zZ0-9\/\_\.]+\"\>/','',$string, 1);

使用回调来执行此操作。如果您将来想根据字符串中不同位置的图像来做一些事情,可能会更灵活一些

class imgReplacer {

    function cb($matches){

        if (!$this->counter){

            $this->counter++;
            return '';

        } else {

            return $matches[0];

        }

    }

}


$ir = new imgReplacer;
$ir->counter = 0;

$string = 'This is my test <img src="link_to_image1">, some other text. <img src="link_to_another_image" border="0">';

$string = preg_replace_callback(
    '#(<img.*?>)#',
    array(&$ir, 'cb'),
    $string);

echo $string;

This is my test , some other text. <img src="link_to_another_image" border="0">

我试着这样做,我得到了答案$feed\u desc=preg\u replace'/]*>/,$str,1;
class imgReplacer {

    function cb($matches){

        if (!$this->counter){

            $this->counter++;
            return '';

        } else {

            return $matches[0];

        }

    }

}


$ir = new imgReplacer;
$ir->counter = 0;

$string = 'This is my test <img src="link_to_image1">, some other text. <img src="link_to_another_image" border="0">';

$string = preg_replace_callback(
    '#(<img.*?>)#',
    array(&$ir, 'cb'),
    $string);

echo $string;

This is my test , some other text. <img src="link_to_another_image" border="0">