If语句解析不正确


If statement parsing incorrectly

我正在尝试将if语句如下所示:如果第一个字符串的位置是.png,那么从干草堆中获取$png1,但是如果第一个字符的位置是.jpg,那么从该干草堆获取$jpg1,但是,如果是.gif,则从干草垛中获取$gif1,否则,如果没有找到它们,则字符串的位置为.bmp,因此获取$bmp1

以下是我尝试过的,但解析不正确:

<?php
// if first occurence is .png get $png1 needle from haystack
if (preg_match('#cid:([^"@]*).png@([^"]*)#', $html_part))           
{           $find = '#cid:([^"@]*).png@([^"]*)#';   
    $replace1 = $png1;
    $html_part = preg_replace($find, $replace, $html_part);
}
// if first occurence is .jpg get $jpg1 needle from haystack
elseif (preg_match('#cid:([^"@]*).jpg@([^"]*)#', $html_part)) 
{           $find = '#cid:([^"@]*).jpg@([^"]*)#';   
    $replace1 = $jpg1;
    $html_part = preg_replace($find, $replace, $html_part);
}
// if first occurence is .gif then get $gif1 needle from haystack
elseif (preg_match('#cid:([^"@]*).gif@([^"]*)#', $html_part)) 
{           $find = '#cid:([^"@]*).gif@([^"]*)#';
    $replace = $gif1;
    $html_part = preg_replace($find, $replace, $html_part);
}
// if first occurence is .bmp then get $bmp1 needle from haystack
else
{           $find = '#cid:([^"@]*).bmp@([^"]*)#';
    $replace = $bmp1;
    $html_part = preg_replace($find, $replace, $html_part);
}
?>

一个示例$html_part,添加换行符用于显示,是:

<b>Bold Text.</b> <i>Italicized Text.</i> <u>Underlined Text.</u> Plain Unformatted Text.
<img width=183 height=183 id="Picture_x0020_3" src="cid:image001.png@01CCCB31.E6A152F0"
alt="Description: Description: Description: cid:image001.png@01CCC701.5A896430">
<img width=153 height=145 id="Picture_x0020_2" src="cid:image002.jpg@01CCCB31.E6A152F0"
alt="Description: Description: cid:image002.jpg@01CCCB1D.D3A29740"><img width=182 height=123
id="Picture_x0020_1" src="cid:image003.jpg@01CCCB31.E6A152F0"
alt="Description: Description: cid:image003.jpg@01CCCB1D.D3A29740">`

如果正则表达式包含不正确,请将'#'替换为'/'。就像这样:

preg_match('/cid:([^"@]*).png@([^"]*)/', $html_part)

更新

我的错误,你的正则表达式很好。我再看一眼。

你能提供一个$html_part的例子吗?

风格提示:与其说多个正则表达式的唯一区别是文件扩展名,不如说:

if (preg_match('#cid:([^"@]*).(gif|png|jpg|bmp)@([^"]*)#', $html_part)) {
    $find = '#cid:([^"@]*).{$html_part[2]}@([^"]*)#';
                           ^^^^^^^^^^^^^^^---captured file extension

并只捕获找到的文件扩展名?这将为您节省4个几乎相同的正则表达式副本,在一个测试周期内完成所有操作

代码中的错误只是

    $replace1 = $png1;
    $html_part = preg_replace($find, $replace, $html_part);

    $replace1 = $jpg1;
    $html_part = preg_replace($find, $replace, $html_part);

-您设置了$replace1,但使用了$replace