问题
I am trying to get this if statement to follow as: if the first string position is .png, then get $png1 from a haystack, but if the first string position is .jpg, then get $jpg1 from the haystack, but if it is .gif, get $gif1 from haystack, else if none of them are found then the string position is .bmp so get $bmp1
Here is what i tried, but it doesn't parse correctly:
<?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);
}
?>
An example $html_part
, with line breaks added for display, is:
<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">`
回答1:
Your regex is not contained correctly, replace the '#' with '/'. So like this:
preg_match('/cid:([^"@]*).png@([^"]*)/', $html_part)
UPDATE
My mistake, your regex is fine. I will have another look.
Can you possibly supply an example of $html_part
?
回答2:
Stylistic tip: instead of multiple regexes whose only difference is the file extension, how about:
if (preg_match('#cid:([^"@]*).(gif|png|jpg|bmp)@([^"]*)#', $html_part)) {
$find = '#cid:([^"@]*).{$html_part[2]}@([^"]*)#';
^^^^^^^^^^^^^^^---captured file extension
and just capture the file extension found? That'd save you having 4 copies of nearly identical regexes, do it all in a single tesing cycle
回答3:
The errors in your code are just
$replace1 = $png1;
$html_part = preg_replace($find, $replace, $html_part);
and
$replace1 = $jpg1;
$html_part = preg_replace($find, $replace, $html_part);
- you set $replace1
, but you use $replace
.
来源:https://stackoverflow.com/questions/9086942/if-statement-parsing-incorrectly