Skip to content

Instantly share code, notes, and snippets.

@imvaskii
Last active June 25, 2018 06:27
Show Gist options
  • Save imvaskii/11eab01028e198c58b80f0fdd6f277b1 to your computer and use it in GitHub Desktop.
Save imvaskii/11eab01028e198c58b80f0fdd6f277b1 to your computer and use it in GitHub Desktop.
Regex to capture attachment ID from image tag markup.
<?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