Удалить тег привязки из строки без исходной ссылки в PHP

Привет ниже моя строка

$str = "It’s been a rough couple of days for <a href='aaa.com'>Apple</a>, as the company is still trying to fix a massive glitch in Facetime that allows consumers to hear audio from users added to group calls before they pick up. It’s not known how long the glitch has existed, but the details of it became widespread knowledge yesterday and prompted Apple to disable the feature entirely. As it turns out, a 14-year-old Arizona teenager discovered the glitch last week while setting up a group chat of Fortnite players, inadvertently finding himself at ground zero for a massive privacy breach debacle.
The teenager discovered the issue on January 20th while setting up a group chat for his friends ahead of a weekend Fortnite session. As he added his pals into the group video chat, he realized that he could hear audio from users he had just added to the group chat before they’d even picked up. He notified his mom, Michele Thompson, who then tried to inform Apple about the glitch.
The <a href='bbb.com'>proactive</a> mother went through several mediums in an effort to garner a response from Apple, including phone, fax, Facebook, and Twitter, where she even tried to reach out to Apple CEO Tim Cook. Unfortunately, none of these mediums garnered an immediate response from Apple.
Source: <a href='sou.com>Source</a>'";

Строка между ними содержит n ссылок (тег привязки), мне нужно удалить все ссылки (тег привязки) из строки, кроме исходной ссылки в конце. ниже я попробовал один

$item = preg_replace('/</?a[^>]*>/','',$str);

Он находит каждую ссылку (тег привязки) и заменяет ее, но в конце мне нужно заменить все ссылки, кроме источника. Любая помощь приветствуется

Есть ли другой доступный способ?

Thiyagarajan 09.03.2019 06:06
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
0
2
91
1

Ответы 1

Используйте DOMДокумент:

$html = <<<EOD
It’s been a rough couple of days for <a href='aaa.com'>Apple</a>, as the company is still trying to fix a massive glitch in Facetime that allows consumers to hear audio from users added to group calls before they pick up. It’s not known how long the glitch has existed, but the details of it became widespread knowledge yesterday and prompted Apple to disable the feature entirely. As it turns out, a 14-year-old Arizona teenager discovered the glitch last week while setting up a group chat of Fortnite players, inadvertently finding himself at ground zero for a massive privacy breach debacle.
The teenager discovered the issue on January 20th while setting up a group chat for his friends ahead of a weekend Fortnite session. As he added his pals into the group video chat, he realized that he could hear audio from users he had just added to the group chat before they’d even picked up. He notified his mom, Michele Thompson, who then tried to inform Apple about the glitch.
The <a href='bbb.com'>proactive</a> mother went through several mediums in an effort to garner a response from Apple, including phone, fax, Facebook, and Twitter, where she even tried to reach out to Apple CEO Tim Cook. Unfortunately, none of these mediums garnered an immediate response from Apple.
Source: <a href='sou.com'>Source</a>
EOD;

$dom = new DOMDocument;
$dom->loadHTML($html);
$aTags = $dom->getElementsByTagName('a');
foreach ($aTags as $aTag) {
    if ($aTag->nodeValue == 'Source') continue;
    $aTag->parentNode->removeChild($aTag);
}
echo $dom->saveHTML();

Другие вопросы по теме