Last active
December 15, 2015 20:48
-
-
Save nidorx/5320792 to your computer and use it in GitHub Desktop.
Altera o target de todos os links de um texto que nao possuem um target definido, para que abram em nova janela.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Classe para permitir passar parametros ao preg_replace_callback | |
| */ | |
| class SimpleCallback | |
| { | |
| private $_params; | |
| private $_callback; | |
| function __construct($callback, $params) | |
| { | |
| $this->_callback = $callback; | |
| $this->_params = $params; | |
| } | |
| public function callback($matches) | |
| { | |
| $call = $this->_callback; | |
| return $call($matches, $this->_params); | |
| } | |
| } | |
| /** | |
| * Altera o target de todos os links de um texto que nao possuem um target | |
| * definido, para que abram em nova janela | |
| * | |
| * Exemplo: | |
| * <pre></code> | |
| * <?php | |
| * $text = ' | |
| * texto texto <a href="http://wikipedia.org" title="Exemplo titulo">Wikipedia</a> texto texto | |
| * texto texto <a class="link" href="http://wikipedia.org" target="alvo">Wikipedia</a> texto texto | |
| * texto texto <a class="link" href="http://alexrodin.info" title="Exemplo titulo">http://alexrodin.info</a> texto texto | |
| * '; | |
| * $allowed = array('http://alexrodin.info','http://static.alexrodin.info'); | |
| * echo setAllTargetBlank($text,$allowed); | |
| * </code></pre> | |
| * | |
| * @param string $text | |
| * @param array $allowedSites Lista de sites permitidos | |
| * @return string | |
| */ | |
| function setAllTargetBlank($text, $allowedSites) | |
| { | |
| $fnCallback = function($matches, $permitidos) { | |
| $params = trim($matches['pre']) . ' ' . trim($matches['post']); | |
| if (!preg_match('#(.*?)target=".*?".*?#', $params)) { | |
| $url = trim($matches['uri']); | |
| if (preg_match('/^[http|https]/', $url)) { | |
| foreach ($permitidos as $link) { | |
| if (strpos($url, $link) === 0) { | |
| return $matches[0]; | |
| } | |
| } | |
| $novoLink = '<a ' . trim($params) . ' href="' . $matches['uri'] . '" target="_blank">' . $matches['text'] . '</a>'; | |
| return $novoLink; | |
| } | |
| } | |
| return $matches[0]; | |
| }; | |
| $objCallback = new SimpleCallback($fnCallback, $allowedSites); | |
| return preg_replace_callback('/<a(?<pre>.*)href="(?<uri>[^" ]*)"(?<post>.*)>(?<text>.*)<\/a>/iU', array($objCallback, 'callback'), $text); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment