K
K
Kornely2021-12-01 01:53:45
PHP
Kornely, 2021-12-01 01:53:45

How to make an exception in regular expression?

There is this code:

$foo = preg_replace('/\[url=([^\s]*)\]\[img(.*?)\]([^\s]*)\[\/img\]\[\/url\]/i', '[img$2]$3[/img]', $foo);

It removes links from images.
How to make it so that for a specific site it does not remove links from images? And removed for the rest.

Thanks in advance for the replies!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dodo512, 2021-12-01
@dodo512

With lookahead (?!...)

$text = preg_replace(
    '#\[url=(?!https?://site\.ru)\S*\](\[img.*?\]\S*\[/img\])\[/url\]#i',
    '$1',
    $text
);

Or with a callback function
$white_list = ['site3.ru', 'site4.ru'];
$text = '
[url=https://site1.ru/page][img]https://site1.ru/file.jpg[/img][/url]
[url=https://site2.ru/page][img]https://site2.ru/file.jpg[/img][/url]
[url=https://site3.ru/page][img]https://site3.ru/file.jpg[/img][/url]
[url=https://site4.ru/page][img]https://site4.ru/file.jpg[/img][/url]
';

$text = preg_replace_callback(
    '#\[url=(\S*)\](\[img.*?\]\S*\[/img\])\[/url\]#i',
    function ($m) use($white_list) {
        $host = parse_url($m[1], PHP_URL_HOST);
        if (in_array($host, $white_list))
            return $m[0];
        
        return $m[2];
    },
    $text
);

sandbox.onlinephpfunctions.com/code/48cddfef32affd...

A
Alexey Dubrovin, 2021-12-01
@alekcena

EM
IF SITE !== "Desired site"
CHECK

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question