[英]Adding negative lookback to this regex pattern in php
我花了整整一天的时间试图弄清楚如何使此代码仅影响运行的第一个实例。 最终,我了解了负面的回溯并尝试实现了这一点。
我尝试了所有可能的安排,当然,除了正确的安排。我发现regex101非常酷,但最终没有帮助我找到解决方案。
$content = preg_replace('/<img[^>]+./','', get_the_content_with_format());
这将在wordpress中使用,以去除页面上的第一张图像(将其移至书面内容上方),而其余部分留在其中,以便在帖子说明中使用图像。
请对我好一点。 这是我的第一个问题,我实际上不是程序员。
更新:因为有人问,这是相关代码的全部内容。
<?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
以使点( .
)与换行符匹配。
如果您只想替换正则表达式匹配项的第一个匹配项,只需将“ 1”添加为第四个参数,这表示将仅替换一个匹配项。 参见http://php.net/manual/de/function.preg-replace.php
在您的示例中,这看起来像:
$content = preg_replace('/<img[^>]+./','', get_the_content_with_format(), 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.