Как сделать замену только в определённом теге?

verfaa

Профессор
Регистрация
29 Янв 2007
Сообщения
416
Реакции
49
Использую PHP 8.2
Есть текст:

HTML:
<p>The random module in Python provides various functions to generate random numbers.</p><h2 id="methods">Generating random numbers within a specific range</h2><p>In Python, generating random numbers within a specific range is a common requirement in various applications.</p>

Я написал код, для замены части слов на заглавные буквы.

PHP:
$res = preg_replace_callback(
        "#(numbers|random|module)#m",
        function (array $matches) {
           return strtoupper($matches[0]);
        },
        $res
    );

Но мне необходимо чтобы эти замены осуществлялись ТОЛЬКО ВНУТРИ тегов <p>. И при этом ничего не менялось внутри тегов <h2> и других тегах.
Как это сделать?
 
PHP:
$res = preg_replace_callback(
    '#(?<=<p>)([^\s].*?)(?=</p>)#s',
    function (array $matches) {
        return preg_replace(
            '#\b(numbers|random|module)\b#i',
            function ($match) {
                return strtoupper($match[0]);
            },
            $matches[0]
        );
    },
    $res
);
 
Код:
$res = '<p>The random module in Python provides various functions to generate random numbers.</p><h2 id="methods">Generating random numbers within a specific range</h2><p>In Python, generating random numbers within a specific range is a common requirement in various applications.</p>';

$res = preg_replace_callback(
    "#(<p>.*?)(numbers|random|module)(.*?</p>)#si",
    function (array $matches) {
        return $matches[1] . strtoupper($matches[2]) . $matches[3];
    },
    $res
);

echo $res;
 
Назад
Сверху