epare it for usage * * @param string $pattern * * @return string */ public function compile_pattern( $pattern ) { return str_replace( array( '%title_tag%', '%capture_quote%', ), array( $this->config['title_tag'], '([\"\\\'])?', ), $pattern ); } /** * Get value of the specific attribute * * @param string $string all attributes of a html element * @param string $attr attribute key * @param bool $default * * @return bool|string attribute value on success or false otherwise. */ public function attr( $string, $attr, $default = false ) { $pattern = '/ %attr% \s* = \s* # find attribute ([\"\'])? # find single or double quote (?(1) (.*?)\\1 | ([^\s\>]+)) # if quote found, match up to next matching /isx'; $pattern = str_replace( '%attr%', $attr, $pattern ); if ( preg_match( $pattern, $string, $match ) ) { return $match[2]; } return $default; } /** * Determine if given id is for featured post image * * @param int|string $id * * @return bool */ public function is_valid_image_id( $id ) { $post = get_post( intval( $id ) ); if ( $post && ! is_wp_error( $post ) ) { return $post->post_type === 'attachment' && substr( $post->post_mime_type, 0, 5 ) === 'image'; } return false; } /** * Look for image in given content and slice important parts * * @param string $content * * @return array { * * @type string $el sound image tag * @type string $src * @type string $link * @type string $id * } */ public function parse_image( $content ) { $result = array( 'caption' => '', 'src' => '', 'link' => '', 'alt' => '', 'id' => '', 'el' => '', 'valid_image_id' => false, ); $pattern = "' (?: # Find figure tag -> Optional (HTML5) < \s*figure.*? > )? (?: # Find link href. -> Optional <\s* a \s+ # a open href\s*=\s* # href attribute %capture_quote% # single or double quote (?(1) (.*?)\\1 | ([^\s\>]+)) # Capture attribute value .*? )? <\s* img \s+ # img tag (.*?) # capture any attribute before class class\s*=\s* # href attribute .*? \b wp\-image\-(\d+) \b .*? ([^\>]+)> # capture any attribute after class (?: # Find link close tag < \s* / \s* a .*? > # Find link close tag )? (?: # Find figcaption tag -> Optional (HTML5) < \s*figcaption .*? > ( .*? ) # Capture inner text < \s* / \s* figcaption .*? > )? (?: # Find figure close tag -> Optional (HTML5) < \s* / \s* figure .*? > )? 'isx"; $pattern = $this->compile_pattern( $pattern ); preg_match( $pattern, $content, $match ); if ( ! empty( $match[0] ) ) { $attr = $match[4] . $match[6]; $result['el'] = $match[0]; $result['src'] = $this->attr( $attr, 'src', '' ); $result['alt'] = $this->attr( $attr, 'alt', '' ); $result['link'] = $match[2]; $result['id'] = $match[5]; $result['caption'] = isset( $match[7] ) ? $match[7] : ''; } return $result; } /** * Trim html string * * @param string $string * * @return string */ public function trim( $string ) { $string = preg_replace( '/( )+$/', '', $string ); return trim( $string ); } }