note 126101 added to function.preg-replace

From: Date: Sat, 22 May 2021 07:37:19 +0000
Subject: note 126101 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-216416@lists.php.net to get a copy of this message
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) use ($baseUrl) { 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 ); } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 154.121.26.240) ---- Manual Page -- https://php.net/manual/en/function.preg-replace.php Edit -- https://main.php.net/note/edit/126101 Del: integrated -- https://main.php.net/note/delete/126101/integrated Del: useless -- https://main.php.net/note/delete/126101/useless Del: bad code -- https://main.php.net/note/delete/126101/bad+code Del: spam -- https://main.php.net/note/delete/126101/spam Del: non-english -- https://main.php.net/note/delete/126101/non-english Del: in docs -- https://main.php.net/note/delete/126101/in+docs Del: other reasons-- https://main.php.net/note/delete/126101 Reject -- https://main.php.net/note/reject/126101 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#216416) next »