在php中为这个正则表达式模式添加负回看


Adding negative lookback to this regex pattern in php

我花了一整天的时间试图弄清楚如何让这段代码只影响它所运行的第一个实例。最后,我学会了消极的回顾,并试图实现它。

我已经尝试了所有可能的安排,当然,除了正确的安排。我发现了regex101,它真的很酷,但最终并没有帮助我找到解决方案。
$content = preg_replace('/<img[^>]+./','', get_the_content_with_format());

这将在wordpress中用于删除页面上的第一个图像(将其移动到书面内容上方),但保留其余部分,以便可以在帖子描述中使用图像。

请对我宽容一点。这是我的第一个问题,我真的不是一个程序员。

Update:因为我问了,这是相关代码的整个块。

<?php
//this will remove the images from the content editor
// it will not remove links from images, so if an image has a link, you will end up with an empty line.
$content = preg_replace('/<img[^>]+./','', get_the_content_with_format());
//this IF statement checks if $content has any value left after the images were removed
// If so, it will echo the div below it.. if not will won't do anything.
if($content != ""):?>
        <div class="portfolio-box">
        <?php echo do_shortcode( $content ) ?>
        </div>
<?php endif; ?>

我已经尝试了这里提供的两种解决方案,但是,不知什么原因,它们都不起作用。

顺便说一句,非常感谢你们的帮助。

您可以将其锚定在字符串的开头(使用^),捕获直到第一张图像(使用(.*?))的所有内容,并将所有内容替换为图像之前的内容:

$content = preg_replace('/^(.*?)<img[^>]+/s','$1', get_the_content_with_format());

注意我还添加了修饰符s,以便点(.)匹配换行符

如果您只想替换第一个出现的regex匹配,只需添加"1"作为第四个参数,这表明只会替换一个匹配。见http://php.net/manual/de/function.preg-replace.php

在您的示例中,它看起来像:

$content = preg_replace('/<img[^>]+./','', get_the_content_with_format(), 1);