flag. * * @var boolean */ private $p_starts = false; /** * Original content ends with
flag. * * @var boolean */ private $p_ends = false; /** * Constructor for specific content taking on replacements for * published keywords. * * @param string $content */ public function __construct( $content ) { $this->content = $content; if ( stripos( $content, '' ) === 0 ) { $this->p_starts = true; } if ( strripos( $content, '
' ) === strlen( $content ) - 4 ) { $this->p_ends = true; } $this->keywords = array(); $keywords = get_posts( array( 'numberposts' => -1, 'post_type' => 'affiliate_keyword', 'meta_key' => 'enabled', 'meta_value' => 'yes' ) ); foreach( $keywords as $keyword ) { $url = get_post_meta( $keyword->ID, 'url', true ); if ( !empty( $url ) ) { $search = $keyword->post_title; $match_case = get_post_meta( $keyword->ID, 'match_case', true ) == 'yes'; if ( $match_case ) { $case = ''; } else { $case = 'i'; } $this->keywords[] = array( 'url' => $url, 'search' => $search, 'case' => $case ); } } } /** * Transforms the content using keyword replacement. * * @return string */ public function get_content() { $charset = get_bloginfo( 'charset' ); $d = new DOMDocument( '1.0', $charset ); // Important to have the right encoding. Either like below or using // sprintf( '', $charset ); $prefix = sprintf( '' ) === 0 ) && !$this->p_starts ) { $this->content = mb_substr( $this->content, 3 ); } if ( ( strripos( $this->content, '
' ) === strlen( $this->content ) - 4 ) && !$this->p_ends ) { $this->content = mb_substr( $this->content, 0, strlen( $this->content ) - 4 ); } } } } return $this->content; } /** * Node traversal and content replacement. * * @param DOMNode $DOMNode */ private function traverse( $DOMNode ) { if( $DOMNode->hasChildNodes() ){ foreach ( $DOMNode->childNodes as $DOMElement ) { $nodeName = $DOMNode->nodeName; $nodeType = $DOMNode->nodeType; if ( $nodeType == XML_ELEMENT_NODE && $nodeName == 'a' ) { // skip links so that we don't place a link inside a link } else { $this->traverse( $DOMElement ); } } } else { $nodeName = $DOMNode->nodeName; $nodeType = $DOMNode->nodeType; if ( $nodeType == XML_TEXT_NODE ) { if ( !empty( $this->current_keyword ) ) { $DOMNode->nodeValue = mb_ereg_replace( '\b' . $this->current_keyword['search'] . '\b', sprintf( '\\0', esc_attr( $this->current_keyword['url'] ) ), $DOMNode->nodeValue, "msr" . $this->current_keyword['case'] ); } } } } }