Поле для ввода УРЛа с протоколом и без

Главные вкладки

Аватар пользователя Sennheiser Sennheiser 17 марта 2020 в 16:49

Есть текстовое поле, куда вводится УРЛ. Необходимо сделать так, чтобы этот урл можно было вводить как с протоколом, так и без.

Выводится эта ссылка в шаблоне:
<a title="Ссылка" href="http://<?php print $URL; ?>">Ссылка</a>
Тут видно, что если ввести урл с протоколом, то ссылка будет не рабочая, так как уже указан http://

Комментарии

Аватар пользователя Sennheiser Sennheiser 18 марта 2020 в 12:33

Но это просто вариант вывода ссылки. Если переменная $URL будет указана баз протокола, то урл будет восприниматься как внутренний.

print l('Ссылка', 'https://newsite.ru'); // Результат – '<a href="https://newsite.ru">Ссылка</a>'
print l('Ссылка', 'newsite.ru'); // Результат – '<a href="https://site.ru/newsite.ru">Ссылка</a>'

Аватар пользователя Sennheiser Sennheiser 18 марта 2020 в 13:07

а нужно, чтобы была возможность писать урл как с протоколом так и без, при этом ссылка должна быть именно на внешний ресурс.

Аватар пользователя sas@drupal.org sas@drupal.org 18 марта 2020 в 14:11

Работает 100% см.

function l($text, $path, array $options = array()) {
  global $language_url;
  static $use_theme = NULL;

  // Merge in defaults.
  $options += array(
    'attributes' => array(),
    'html' => FALSE,
  );

  // Append active class.
  if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
      (empty($options['language']) || $options['language']->language == $language_url->language)) {
    $options['attributes']['class'][] = 'active';
  }

  // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
  // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
  if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
    $options['attributes']['title'] = strip_tags($options['attributes']['title']);
  }

  // Determine if rendering of the link is to be done with a theme function
  // or the inline default. Inline is faster, but if the theme system has been
  // loaded and a module or theme implements a preprocess or process function
  // or overrides the theme_link() function, then invoke theme(). Preliminary
  // benchmarks indicate that invoking theme() can slow down the l() function
  // by 20% or more, and that some of the link-heavy Drupal pages spend more
  // than 10% of the total page request time in the l() function.
  if (!isset($use_theme) && function_exists('theme')) {
    // Allow edge cases to prevent theme initialization and force inline link
    // rendering.
    if (variable_get('theme_link', TRUE)) {
      drupal_theme_initialize();
      $registry = theme_get_registry(FALSE);
      // We don't want to duplicate functionality that's in theme(), so any
      // hint of a module or theme doing anything at all special with the 'link'
      // theme hook should simply result in theme() being called. This includes
      // the overriding of theme_link() with an alternate function or template,
      // the presence of preprocess or process functions, or the presence of
      // include files.
      $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
      $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
    }
    else {
      $use_theme = FALSE;
    }
  }
  if ($use_theme) {
    return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
  }
  // The result of url() is a plain-text URL. Because we are using it here
  // in an HTML argument context, we need to encode it properly.
  return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
}

Аватар пользователя Sennheiser Sennheiser 19 марта 2020 в 9:22

Спасибо, но такой вариант не пойдет.

Во-первых // перед сайтом - это протокол текущего сайта, на котором ссылка стоит, то есть если на сайте с https протоколом стоит ссылка с урлом //site.ru, то эта ссылка будет вести именно на https://site.ru. Она не сработает если site.ru имеет незащищенный протокол http.

Во-вторых задача стоит именно в том, чтобы урл в поле можно было вставлять как копированием из адресной строки браузера (с протоколом), так и обычным ручным набором для пользователей, (site.ru, www.site.ru)

Аватар пользователя Sennheiser Sennheiser 20 марта 2020 в 16:28

)) Ну так задача стоит именно в том, чтобы урл в поле можно было вставлять как копированием из адресной строки браузера (с протоколом), так и обычным ручным набором для пользователей, (site.ru, www.site.ru)

Аватар пользователя marassa marassa 20 марта 2020 в 17:46

А я бы проверял и исправлял на этапе заполнения поля. Мало ли в каких случаях и контекстах потом придется это поле отображать.

Аватар пользователя Sennheiser Sennheiser 20 марта 2020 в 18:16

ок, тогда проще привести к единому формату. Отсюда вопрос. Как массово добавить к имеющимся значениям поля http:// ?