note 126100 deleted from function.preg-replace by cmb

From: Date: Sat, 22 May 2021 10:36:14 +0000
Subject: note 126100 deleted from function.preg-replace by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-216418@lists.php.net to get a copy of this message
Note Submitter: arvodia at hotmail dot com ---- Function which allows to add nofollow automatically and to keep the other attributes <?php function nofollow(string $html, string $baseUrl = null) { return preg_replace_callback( '#<a([^>]*)>(.+)</a>#isU', function ($mach) { list ($a, $attr, $text) = $mach; if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) { $url = $url[1]; if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) { if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) { $relAttr = $rel[0]; $rel = $rel[1]; } $rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"'; $attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel; $a = '<a ' . $attr . '>' . $text . '</a>'; } } return $a; }, $html ); } ?>

« previous php.notes (#216418) next »