Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Detect and format music chords in a document
<?php
function fjarrett_format_chords( $content ) {
$new_content = null;
$pattern = '/\b[A-G](?:##?|bb?)?(?:min|m)?(?:maj|add|sus|aug|dim)?[0-9]*(?:\/[A-G](?:##?|bb?)?)?(?!\S)/';
// Iterate over each line in the document
foreach ( preg_split( '/((\r?\n)|(\r\n?))/', $content ) as $line ) {
// Find chords on this line
preg_match_all( $pattern, $line, $matches );
// Only format the chords if this line consists of only chords
if ( str_word_count( $line ) === count( $matches[0] ) ) {
$line = preg_replace( $pattern, '<span class="chord">$0</span>', $line );
}
// Wrap each line in a paragraph
$new_content .= sprintf( '<p>%s</p>', empty( $line ) ? '&nbsp;' : $line );
}
// Format text for monospaced output
printf( '<pre>%s</pre>', $new_content );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment