How to Cut Certain Links from Text?

There is a list of allowed links if they have something to find them and make active if there are no references in the list, then you need to remove it. Headed here a bit, that’s what happened

$text = ',   http://ya.ru, google.ru   www.site.org/page.php?id=133.';
$links = file('link.txt');
$regex = "/((http:\/\/|https:\/\/)?([a-z0-9\-\.]+)?[a-z0-9\-]+(!?\.[a-z]{2,4}))/";
preg_match_all($regex, $text, $text_link);
for ($i = 0; $i < count($text_link[0]); $i++) {
    for ($a = 0; $a < count($links); $a++) {
        if (trim($text_link[0][$i]) == trim($links[$a])) {
            $text = preg_replace('/(http:\/\/|https:\/\/)?' . trim($links[$a]) . '/',
                '<a href="' . $links[$a] . '">' . $links[$a] . '</a>', $text);
        } else {
            $text = preg_replace('/(http:\/\/|https:\/\/)?' . trim($links[$a]) . '/',
                '[error]', $text);
        }
    }
}
echo $text;

It works not correctly, replaces not as you need, help cope with the problem


Answer 1, Authority 100%

Try replacing:

$regex = "@(https?://)?(([a-z0-9.-]+)?[a-z0-9-]+(!?\.[a-z]{2,4}))@";

And think about using preg_ replace _callback

$links = array(
        'ya.ru'         => "",
        'yandex.ru'     => "",
        'google.ru'     => "",
        'google.com'    => "",
);
function replace_link( $matches ) {
        global $links;
        if (isset($matches[2]) and !empty($matches[2])) {
                if (isset($links[$matches[2]])) {
                        $rc = '<a href="';
                        if (empty($matches[1])) {
                                $rc .= 'http://';
                        }
                        $rc .= $matches[0];
                        $rc .= '">';
                        $rc .= $matches[2];
                        if (isset($matches[3])) {
                                $rc .= $matches[3];
                        }
                        $rc .= '</a>';
                        $matches[0] = $rc;
                }
                else {
                        $matches[0] = "[error]";
                }
        }
        return $matches[0];
}
$text = ',   http://ya.ru, google.ru   www.site.org/page.php?id=133.';
$regex = "@(https?://)?([a-z0-9.-]{3,})(/[^\s]*)[email protected]";
echo "Before:\n", $text, "\n";
$text = preg_replace_callback( $regex, 'replace_link', $text );
echo "After:\n", $text, "\n";