SO网友:Stephen M. Harris
其他答案并非在所有情况下都有效和/或在不应该和/或不可靠地检查rel
属性(如果存在)。
此解决方案更全面,允许更大的灵活性。
// Takes an string of html attr and adds an attribute value; if attr is present and $replace=false, space and the new value is added to end of the attribute; otherwise attr is added to end.
function inject_html_attr($attr_str, $new_attr_name, $attr_value, $replace=false) {
return preg_replace_callback(
\'/(((?:^|\\s)\'.$new_attr_name.\'=[\\\'"])(.*?))([\\\'"])|$/i\',
function($m)use($new_attr_name,$attr_value, $replace){
if( $m[0] ){
$m[1] = $replace ? $m[2] : $m[1].($m[3]?\' \':\'\');
}else{
$m[1] = \' \'.$new_attr_name.\'="\';
$m[4] = \'"\';
}
return $m[1].$attr_value.$m[4];
},
$attr_str, 1 );
}
add_filter(\'the_content\', \'apply_external_link_markup\');
function apply_external_link_markup($content) {
// Assumes attributes are quoted (single or double)
return preg_replace_callback(
\'/<a ([^>]*)(href=(["\\\'])(?:https?:)?\\\\/\\\\/([^\\\\/\\\'">]+)(.*?)\\3)([^>]*)>/i\',
function($m) {
if( $m[4] === $_SERVER[\'HTTP_HOST\'] )
return $m[0];
$attr = \' \'.trim(trim($m[1]).\' \'.trim($m[6]));
//$attr = inject_html_attr( $attr, \'class\', \'external-link\' );
//$attr = inject_html_attr( $attr, \'target\', \'_blank\', true );
$attr = inject_html_attr( $attr, \'rel\', \'nofollow\', true );
return \'<a \'.$m[2].$attr.\'>\';
},
$content );
}