Replace any text from html text by tag name with specific attribute in php

function replace_tag_with_specific_attr_type( $tagAttribute, $tagAttributeValue, $subjectStr, $tagName=null,$replaceStr ) { if( is_null($tagName) ) $tagName = ‘\w+'; else $tagName = preg_quote($tagName); $tagAttribute = preg_quote($tagAttribute); $tagAttributeValue = preg_quote($tagAttributeValue); $match_regex = “/<(“.$tagName.”)[^>]*$tagAttribute\s*=\s*”. “([‘\”])$tagAttributeValue\\2[^>]*>(.*?)<\/\\1>/”; preg_match_all($match_regex, $subjectStr, $matches, PREG_PATTERN_ORDER); $result = str_replace($matches[3],$replaceStr,$subjectStr); return $result; } Usage :