检查第一段是否为图像,然后紧跟其后显示自定义代码?

时间:2012-05-19 作者:its_me

我想在函数中添加一些代码。实现此功能的php:

如果第一段包含图像,请在其后面显示我的自定义代码。例如:

<div class="entry-content">
    <p><img src="http://example.com/example.jpg" alt="Image in 1st para" /></p>
    <div>MY CUSTOM CODE</div>
</div>
但如果第一段是文本(即不是图像),请在其前面显示我的自定义代码。

<div class="entry-content">
    <div>MY CUSTOM CODE</div>
    <p>This 1st paragraph contains text, not an image.</p>
</div>
我该怎么做?最受欢迎的示例代码片段。

PS: 自定义代码也可以是广告(例如Google Adsense)。

3 个回复
最合适的回答,由SO网友:Bainternet 整理而成

用jQuery写几行简单的代码怎么样?

jQuery(document).ready( function ($) {
    if ($(".entry-content:first-child").has(\'img\').length) //this check for the img tag
        $(".entry-content:first-child").after("<div>MY CUSTOM CODE</div>");
    else
        $(".entry-content:first-child").before("<div>MY CUSTOM CODE</div>");
});

Update:

下面是一个使用php本机的简单解决方案DOMDocument

add_filter(\'the_content\',\'add_code_before_afterImage\');

function add_code_before_afterImage($content){
    $MYCODE = \'<div>this is my custom code</div>\';
    $doc = new DOMDocument();
    @$doc->loadHTML(\'<?xml encoding="\'.get_bloginfo(\'charset\').\'">\'.$content);
    $ps = $doc->getElementsByTagName(\'p\');
    foreach ($ps as $p) {
        if (false !== stripos($p->nodeValue,\'img\'));
            return str_replace($p->nodValue, $p->nodValue.$MYCODE, $content);
        }
        break;
    }
    //if we got here then there is no img tag in the first paragraph
    //so we return the code before the content.
    return $MYCODE.$content;
}

Update 2:

@Sarathi的评论让我想到,你实际上不需要解析内容的任何部分,只需拉取第一段并检查它是否有img标记,因此这里有一个更简单、更快的解决方案,只需使用PHP的本机str_replacestripos

add_filter(\'the_content\',\'simple_img_tag_search\');
function simple_img_tag_search($content){

    $MYCODE = \'<div>this is my custom code</div>\';

    //split content to first paragraph and the rest
    $paragraphs = explode( \'</p>\', $content, 2 );

    //extract the first paragraph
    $first_paragraph = $paragraphs[0];

    //then just look for img tag
    if (false === stripos($first_paragraph, "<img")){
        //not found then just return the code before the content
        return $MYCODE.$content;
    }else{
        // img tag found so we return the code after the first paragraph
        return str_replace($first_paragraph.\'</p>\',$first_paragraph.\'</p>\'.$MYCODE,$content);
    }
}

SO网友:fuxia

抓住第一段(<p>) 您可以使用正则表达式。那是not optimal, 因此,请注意。:)

然后测试图像的匹配,并根据测试结果插入额外的内容。我在这里使用两个函数,每个步骤一个:第一个查找第一段,第二个更改第一个匹配。

// Late priority parameter to let shortcodes and other filters do their work first.
add_filter( \'the_content\', \'wpse_52662_add_extra\', 1000 );

/**
 * Reads the content and calls a callback to add extra content.
 *
 * @param  string $content
 * @return string
 */
function wpse_52662_add_extra( $content )
{
    // restrict to single posts:
    if ( ! is_single() )
    {
        return $content;
    }

    return preg_replace_callback(
        \'~<p(>|\\s+[^>]*>)(.*?)</p>~miU\' // find <p>
    ,   \'wpse_52662_callback\'           // pass the result to the callback
    ,   $content
    ,   1                               // stop after first match
    );
}

/**
 * Callback for wpse_52662_add_extra()
 *
 * @param array $m Matches. $m[0] contains the whole match,
 *                          $m[2] the content of the paragraph.
 * @return string
 */
function wpse_52662_callback( $m )
{
    $extra = \'<p><b>Hello World!</b></p>\';
    return ( FALSE === strpos( $m[2], \'<img\' ) ) ? $extra.$m[0] : $m[0].$extra;
}

SO网友:Sarathi

您可以使用DOMDocument解析HTML内容,如下所示:

add_filter( \'the_content\', \'add_html_after_first_image\' );
function add_html_after_first_image( $content ) {

    $my_custom_html = \'<div>MY CUSTOM CODE</div>\';

    // Create a dom document from the post content.
    // The content needs to be wrapped in a root element to be valid xml, hence the div tags.
    // I used loadXML because loadHTML adds the unnecessary <DOCTYPE>, <html>, and <body>.
    if( $dom = DOMDocument :: loadXML( \'<div>\' . $content . \'</div>\' ) ) {

        // Create a document fragment with your custom html.
        $custom = $dom -> createDocumentFragment();
        $custom -> appendXML( $my_custom_html );

        // Get the root element, and first child.
        $root   = $dom  -> firstChild;
        $first  = $root -> firstChild;

        // Check if the first child is a paragraph, the first grandchild is an image,
        // and if the paragraph has no content other than the image.
        $has_image = \'p\'   == $first -> tagName
                &&   \'\'    == trim( $first -> textContent )
                &&   1     == count( $first -> childNodes )
                &&   \'img\' == $first -> firstChild -> tagName;

        // If $has_image is true then add the custom div after the first paragraph,
        // otherwise add it before.
        $root -> insertBefore( $custom, $has_image ? $first -> nextSibling : $first );

        // Set the new content to the altered html.
        $content = $dom -> saveHTML();
    }

    return $content;
}

EDIT:

这是一个经过优化的更新函数,它比上面的函数运行得更快。

提示:<;p>;标签不得包含除以下内容以外的任何内容(<;img/>;标签(包括空格)

add_filter( \'the_content\', \'add_html_after_first_image\' );
function add_html_after_first_image( $content ) {

    $my_custom_html = \'<div>MY CUSTOM CODE</div>\';

    // Explode the content to extract and parse only the first paragraph.
    $parts = explode( \'</p>\', $content, 2 );
    $p = $parts[0] . \'</p>\';

    // Create a dom document from the first paragraph of content.
    // I used loadXML because loadHTML adds the unnecessary <DOCTYPE>, <html>, and <body>.
    // Checking for an opening <p> tag prevents the creation of a DOMDocument,
    // and lowers the execution time on posts that don\'t start with a paragraph.
    if( substr( $p, 0, 3 ) == \'<p>\' && $dom = @DOMDocument :: loadXML( $p ) ) {

        // Create a document fragment with your custom html.
        $custom = $dom -> createDocumentFragment();
        $custom -> appendXML( $my_custom_html );

        $first  = $dom -> firstChild;

        // Check if the first child is a paragraph, the first grandchild is an image,
        // and if the paragraph has no content other than the image.
        $has_image = \'p\'   == $first -> tagName
                &&   \'\'    == $first -> textContent
                &&    1    == count( $first -> childNodes )
                &&   \'img\' == $first -> firstChild -> tagName;

        // If $has_image is true then add the custom div after the first paragraph,
        // otherwise add it before.
        $dom -> insertBefore( $custom, $has_image ? $first -> nextSibling : $first );

        // Set the new content to the altered html.
        $p = $dom -> saveHTML();

    }
    // If the dom document could not be created, then the first element is not a
    // paragraph and the custom code should be prepended to the content.
    else $p = $my_custom_html . $p;

    // Append the rest of the content to the paragraph.
    return $p . $parts[1];
}

结束

相关推荐