Last active
June 25, 2018 06:27
-
-
Save imvaskii/11eab01028e198c58b80f0fdd6f277b1 to your computer and use it in GitHub Desktop.
Regex to capture attachment ID from image tag markup.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns attachment ids from the string using regex. | |
* match string "wp-image-{the-id-here}" | |
* regex101 link: https://regex101.com/r/aacOaV/1/ | |
* | |
* @param string $content | |
* @return array array of attachment ids. | |
*/ | |
public function get_attachment_ids_from_content( $content ) { | |
$re = '/wp-image-([0-9]+)/mi'; | |
preg_match_all( $re, $content, $matches, PREG_SET_ORDER, 0 ); | |
$attachment_ids = []; | |
foreach ( $matches as $match ) { | |
if ( is_numeric( $match[1] ) ) { | |
$attachment_ids[] = (int) $match[1]; | |
} | |
} | |
return $attachment_ids; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment