Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjarrett/3d5095fcfd39b55f639e to your computer and use it in GitHub Desktop.
Save fjarrett/3d5095fcfd39b55f639e to your computer and use it in GitHub Desktop.
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