How to add a function with a regular expression to define links and replace them so that the anchor is a domain, for example, the function below makes, for example,

http://youtube.com/video123123 

-

 <a href='http://youtube.com/video123123'>http://youtube.com/video123123</a> 

And I need to get

 <a href='http://youtube.com/video123123'>youtube.com</a> 

-

 preg_replace_callback( '{ (?: (\w+://) # протокол с двумя слэшами | # - или - www\. # просто начинается на www ) [\w-]+(\.[\w-]+)* # имя хоста \S* # URI (но БЕЗ кавычек) (?: # последний символ должен быть... (?<! [[:punct:]] ) # НЕ пунктуацией | (?<= [-/&+*] ) # но допустимо окончание на -/&+* ) }xis', create_function ( '$match', // Если нет протокола, добавляем его в начало строки. '$href = !empty($match[1])? $match[0] : "http://".$match[0]; // Формируем ссылку. return \'<a href="\'.$href.\'" target="_blank">\'.$match[0].\'</a>\';' ), $text ) 

Thank you in advance.

  • make var_dump ($ match [0]), most likely it is match 1 - lampa
  • @ola_sh, To format a code, select it with the mouse and press the {} button of the editor. - Nicolas Chabanovsky

1 answer 1

 $result = preg_replace_callback("# ^ (https?://) # группа (1) протокол (?:www\.)? ([\w-]+(\.[\w-]+)) # группа (2), то что вы хотите видеть в результате внутри тега <a/> *\S*(?:(?<! [[:punct:]])|(?<= [-/&+*]))$#", # без изменений, на ваше усмотрение create_function( '$matches', '$href = empty($matches[1]) ? "http://{$matches[0]}" : $matches[0]; return "<a href=\"$href\">$matches[2]</a>"; ), "http://php.net/manual/en/function.preg-replace-callback.php"); 

By the way, in my opinion, you can disregard the protocol, and without checks there is or not just to substitute "http: //". With "http", it is quite normal to redirect to "https".

  • Not all sites redirect to HTTPS - Vladimir Klykov