<?php
/**
 * Plugin Name: An example How to rewrite part of an href attribute
 * Plugin URI: http://nourl.com
 * Author: para
 * Version: 0.1
 */


/**
 * This example will rewrite 'en-US' to 'de-DE' in all found 'href' attributes of 'a' html elements
 */
add_action('plugins_loaded', function () {

    /**
     * using \Smartling\Base\ExportedAPI::EVENT_SMARTLING_AFTER_DESERIALIZE_CONTENT action
     */
    add_action('smartling_after_deserialize_content', function ($params) {
        // This code will be executed every time when WP Connector applies translated content 
        // to post\pages\etc for every locale
        $logger = \Smartling\Bootstrap::getLogger();
        /**
         * @var \Smartling\Helpers\EventParameters\AfterDeserializeContentEventParameters $params
         */
        array_walk_recursive($params->getTranslatedFields(), function (& $value) use ($params, $logger) {
            $linkRegexp = '<a.*?href=(["\']).*?(en-US).*?\1.*?>';
            // Get target locale code
            $replacement = $params->getSubmission()->getTargetLocale();
            $value = preg_replace_callback($linkRegexp, function ($matches) use ($params, $replacement, $logger) {
                // $matches[0] contains full <a> tag
                // $matches[2] contains "en-US" which should be replaced
                $result = preg_replace('/(' . $matches[2] . ')/', $replacement, $matches[0]);
                $logger->debug(vsprintf('URL_REPLACE: Replacing \'%s\' with \'%s\'', [$matches[0], $result]));

                return $result;
            }, $value);
        });

        return $params;
    });
});