'How to remove all href link but exclude some specific href links
<?php $string = 'this is just testing <a href="https://twitter.com/blalala/status/1523867438743711744">twitter</a> visit google <a href="https://www.google.com/search?q=stack+overflow">google</a> this is twitter <a href="t.co/blalala/status/1523867438743711744"> short URL</a> this is URL for stack over <a href="https://stackoverflow.com/">stack overflow</a>';
echo preg_replace('#<a.*?>([^>]*)</a>#i', '$1', $string);
?>
Current output
this is just testing twitter visit google google this is twitter short URL this is URL for stack over stack overflow
current code remove all href URL and keep only anchor text,
I want preg replace for ignore twitter.com and t.co URL from string
**Desire out should be:- **
this is just testing twitter visit google google this is twitter this is twitter short URL this is URL for stack over stack overflow"
I only want clickable links of Twitter and t.co that's It, I hope you will understand
Solution 1:[1]
You can try this: Find all links (matching your expression), loop through links and check if they contain one of the "allowed" keywords you define in an array. In that case, continue, otherwise remove that link from the string.
<?php
$string = 'this is just testing <a href="https://twitter.com/blalala/status/1523867438743711744">twitter</a> visit google <a href="https://www.google.com/search?q=stack+overflow">google</a> this is twitter <a href="t.co/blalala/status/1523867438743711744"> short URL</a> this is URL for stack over <a href="https://stackoverflow.com/">stack overflow</a>';
$allowed = array("twitter.com","t.co");
preg_match_all('#<a.*?>([^>]*)</a>#i', $string, $matches);
foreach($matches[0] AS $link){
foreach($allowed AS $site){
if(strpos($link, $site) !== false){
continue 2;
}
}
$string = str_replace($link, '', $string);
}
echo $string;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicola Fiorello |
