Добавить новый класс в div с помощью DOMDocument

#php

#php

Вопрос:

Я начинающий веб-разработчик. У меня есть этот код:

 $content = '<div class="textowaTrescTresc ">
        <p><strong>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of
                classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin
                professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
                consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical
                literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of
                "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book
                is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem
                Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.Contrary to popular belief,
                Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC,
                making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in
                Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and
                going through the cites of the word in classical literature, discovered the undoubtable source. Lorem
                Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good
                and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
                during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line
                in section 1.10.32.</strong></p>



        <blockquote>
            Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical
            Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
            section 1.10.32.
        </blockquote>

        <p>xxxx<img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="dupa"
                data-label-class="label-class"></p>

        <h4>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical
            Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
            section 1.10.32.</h4>

        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin
            literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
            section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece
            of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin
            professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur,
            from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the
            undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
            (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of
            ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..",
            comes from a line in section 1.10.32.</p>



        <p><img alt="this is super nice image with lablethis is super nice image with lable 2" src="2.jpg"
                style="height:560px; width:840px">

        </p>

        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin
            literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
            section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece
            of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin
            professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur,
            from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the
            undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
            (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of
            ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..",
            comes from a line in section 1.10.32.</p>

        <p><img alt="this is super nice image with lable 3" src="3.jpg" style="height:478px; width:840px"></p>



        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin
            literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in
            section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece
            of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin
            professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur,
            from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the
            undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
            (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of
            ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..",
            comes from a line in section 1.10.32.</p>
        <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical
            Latin
            literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at
            Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a
            Lorem
            Ipsum passage, and going through the cites of the word in classical literature, discovered the
            undoubtable
            source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The
            Extremes
            of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very
            popular
            during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line
            in
            section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a
            piece
            of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin
            professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
            consectetur,
            from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered
            the
            undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et
            Malorum"
            (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of
            ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit
            amet..",
            comes from a line in section 1.10.32.</p>

        <p><img alt="this is super nice image with lable 4" src="5.jpg" style="height:560px; width:840px">
        </p>

    </div>';



$content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');

$doc = new DOMDocument();
$doc->loadHTML($content);
$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
    $old_src = $tag->getAttribute('src');
    $tag->setAttribute('data-label-class', 'label-class');
    $tag->setAttribute('class', 'picla');
}

$content = $doc->saveHTML();

echo $content;
  

Это работает нормально, но у меня есть 2 небольшие проблемы:

  1. Если у меня уже есть класс в IMG — текущий php-код удаляет предыдущий класс и добавляет только новый (picla). Хотелось бы, чтобы они оба были доступны (как старые классы, так и picla).
  2. Я бы хотел, чтобы класс .picla добавлялся только тогда, когда изображение имеет атрибут «alt». Если это не так, не добавляйте класс .picla.

Как я могу это сделать?

Пожалуйста, помогите мне.

Например, в строке у меня есть:

 <img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="dupa" data-label-class="label-class"> 
  

После моего php-скрипта у меня есть:

 <img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="picla" data-label-class="label-class"> . 
  

Правильный результат:

 <img alt="Description 2" src="1.jpg" style="height:560px; width:840px" class="dupa picla" data-label-class="label-class">
  

(2 класса)

Комментарии:

1. Вы говорите об изменении класса для <div> , и все же ваш код выбирает только <img> элементы. Можете ли вы также удалить много <p> элементов в примере HTML, если они не помогают показать проблему. После сокращения до пары тегов, которые показывают, что вы хотите изменить, можете ли вы затем показать, как должен выглядеть результат.

2. Я обновляю свой первый пост

3. Вы можете использовать, hasAttribute чтобы проверить, есть ли alt там, не извлекая его.

Ответ №1:

Добавить необходимые проверки для alt и class атрибутов:

 foreach ($tags as $tag) {
    // get value of an `alt` attribute
    $alt = $tag->getAttribute('alt');
    
    if (!empty($alt)) {
        // get current class(es)
        $class = $tag->getAttribute('class');
        if (!empty($class)) {
            $class .= " picla";
        } else {
            $class = "picla";
        }
        $tag->setAttribute('class', $class);
    }
    // other code here
}
  

Здесь простая скрипка.

Комментарии:

1. Не уверен, что вам нужно остальное — я бы хотел, чтобы класс .picla добавлялся только тогда, когда изображение имеет атрибут «alt». Если этого не произойдет, не добавляйте класс .picla .

2. Я устанавливаю только один класс в else, если атрибут alt не пуст.