[英]Combining an if statement with regular expressions
當前代碼,搜索第一個image
和第一個iframe
。 但是,我希望它僅顯示找到的第一個,而不是兩個都顯示的第一個。 如果首先找到iframe
,請顯示該內容。 如果image
顯示出來。
function first_item() {
global $post, $posts;
$first_item = '';
ob_start();
ob_end_clean();
if ( preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)) {
$first_item = $matches [1] [0];
echo "<img src=" . $first_item . ">";
} if (preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)) {
$first_item = $matches [1] [0];
echo "<iframe src=" . "'" . $first_item . "'" . "/" .">" . "</iframe>";
} }
任何幫助都會很棒。
由於兩者都使用src
屬性,因此您可以采取捷徑:
'/<(img|iframe).+src=...............................>/i'
但是請注意,小馬正在注視着……
無需使用preg_match_all,只需為單個匹配使用preg_match:
$pattern = <<<'LOD'
~
## begining of the tag ##
<i (mg|frame) \b # capture group 1: to know which tag name it is
## all possible content before the src attribute ##
(?>
[^s>]++ # all that is not a "s" or a ">" (to fail at the tag end)
|
\B s++ # "s" without a word boundary can't be the "s" from "src"
|
s (?!rc \s*+ =) # "s" not followed by "rc="
)++ # repeat the group one or more times
# (there is at least a space)
## from the attribute name until the begining of the attribute value ##
src \s*+ = \s*+ ["']?+ # spaces and quote are optional
## attribute value ##
( [^\s"'>]++ ) # capture group 2: url
# the value can't contain spaces, quotes, or >, since it is
# an URL
~ix
LOD;
if (preg_match($pattern, $post->post_content, $match)) {
$first_item = $match[2];
if ($match[1]=='mg')
echo '<img src="' . $first_item . '"/>';
else
echo '<iframe src="' . $first_item . '"></iframe>';
}
獲得兩個匹配項,找到最先出現的匹配項,並顯示出來。
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $img_matches, PREG_OFFSET_CAPTURE);
preg_match('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $iframe_matches, PREG_OFFSET_CAPTURE);
if ($img_matches[0][1] < $iframe_matches[0][1]) {
echo "image first";
}
else {
echo "iframe first";
}
假定圖像和iframe都在內容中。 否則,請檢查匹配項是否首先找到任何內容。
我創建一個示例,希望這會有所幫助:
function catch_that_image() {
global $post, $posts;
$first_img = '';
$iframe = '';
$link = get_permalink($postID);
ob_start();
ob_end_clean();
$first_img_output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $first_img_matches);
$first_img = $first_img_matches[1][0];
$iframe_output = preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*><\/iframe>/i', $post->post_content, $iframe_matches);
$iframe = $iframe_matches[1][0];
if ( $first_img < $iframe ) {
echo('<div class="fluid-width-video-wrapper" style="padding-top: 56.25%;"><iframe src="' . $iframe . '" frameborder="0" allowfullscreen></iframe></div>');
} else {
echo '<a href="'.$link.'" class="block-thumb">';
echo('<img src="'.$first_img.'">');
echo '</a>';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.