php - Remove all attributes except href and target (if target != '') from all anchor tags
Get the solution ↓↓↓I have a html string and needs to remove all anchor tag's attribute except href and target ( if target has a valid value ).
$content = '<p style="abc" rel="blah blah"> Hello I am p </p> <a href="https://example.com/abc" target="_blank" rel="noopener noreferrer"></a>';
I have created a regex for the same -
preg_replace('/<a\s+[^>]*href\s*=\s*"([^"]+)"[^>]*>/', '<a href="\1">', $content)
But this remove target attribute as well even though it has valid value ( _blank ).
For example -
<a href="https://example.com/abc" target="_blank" rel="noopener noreferrer"></a>
should return
<a href="https://example.com/abc" target="_blank"></a>
AND
<a href="https://example.com/abc" target="" rel="noopener noreferrer"></a>
should return
<a href="https://example.com/abc"></a>
Answer
Solution:
Try with the following regex:
preg_replace('/(\s?target=(?:""))?(\srel.+")\s?/', ' ', $content)
I only tested with the two examples you have provided, if not working for some patterns please share some examples.
note: Online demo for testing
Answer
Solution:
You can take a different approach. Like extract only thetarget
attribute and the element content then create a new element with them.
$content = '<a href="https://example.com/abc" target="_blank" rel="noopener noreferrer">click here</a>';
// Extract the content.
$value = array();
$has_value = preg_match( '/<[^<>]+>([^<>]*)<\/[^<>]+>/', $content, $value );
if ( $has_value ) {
$value = $value[1];
} else {
$value = '';
}
// Extract the target attribute.
$target_attr = array();
$has_target = preg_match( '/[\s<]target="[^"]+"[\s>]/', $content, $target_attr );
if ( $has_target ) {
$target_attr = $target_attr[0];
} else {
$target_attr = '';
}
$new_content = "<a $target_attr>$value</a>";
Output:
<a target="_blank" >click here</a>
Hope it helps :)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: failed to create image decoder with message 'unimplemented'
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.