<?php

/**
 * Content
 * @category Functions
 * @author Krik
 */

add_filter('the_content', 'krik_content');

function krik_content($content) {
	// Lazy load images
	$content = preg_replace('/<img(.*?)(src=)(.*?)>/i', '<img$1data-$2$3>', $content);
	$content = preg_replace('/<img(.*?)(srcset=)(.*?)>/i', '<img$1data-$2$3>', $content);
	$content = preg_replace('/<img(.*?)class=\"(.*?)\"(.*?)>/i', '<img$1class="$2 lazy"$3>', $content);
	$content = preg_replace('/<img(.*?)(?!\bclass\b)(.*?)/i', '<img$1 class="lazy"$2', $content);

	// Target _blank for external links
	$pattern = '/<a(.*?)?href=[\'"]?[\'"]?(.*?)?>/i';

	$content = preg_replace_callback($pattern, function($matches) {
		$match = array_shift($matches);
		$link = isset($matches[1]) ? $matches[1] : null;

		if (preg_match('/target=[\'"]?(.*?)[\'"]?/i', $match)) return $match;
		if (trim($link) && strpos($link, env('WP_DOMAIN')) !== false) return $match;
		if (trim($link) && strpos($link, '/') === 0) return $match;
		if (trim($link) && strpos($link, '#') === 0) return $match;

		return preg_replace_callback('/href=/i', function($matches2) {
			return sprintf('target="_blank" %s', array_shift($matches2));
		}, $match);
	}, $content);

	return $content;
}
