Skip to content

Instantly share code, notes, and snippets.

@fumikito
Last active July 4, 2017 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumikito/f3203b4cd8162b5efb9f166d85b5d35e to your computer and use it in GitHub Desktop.
Save fumikito/f3203b4cd8162b5efb9f166d85b5d35e to your computer and use it in GitHub Desktop.
WordPressからlet's punctuateを利用するgist
<?php
/**
* Tokenize string to morphemes.
*
* @param string $string
* @return array
*/
function hametuha_punctuate( $string ) {
try {
// Use cache if exists.
$parsed = wp_cache_get( $string, 'tokens' );
if ( false === $parsed ) {
// Cache not found, so try request.
$endpoint = 'https://punctuate.space/json?q='.rawurlencode( $string );
$response = wp_remote_get( $endpoint );
if ( is_wp_error( $response ) ) {
throw new Exception( $response->get_error_message() );
}
$parsed = json_decode( $response['body'] );
if ( ! $parsed ) {
throw new Exception( 'Malformed response.' );
}
wp_cache_set( $string, $tokens, 'tokens' );
}
return $parsed;
} catch( Exception $e ) {
// Failed, so returns single as single token.
return [ $string ];
}
}
/**
* Echo tokenized string
*
* Don't forget adding style like below
* ```
* .token{
* display: inline-block;
* }
* ```
*
* @param string $string
*/
function hametuha_the_punctuate( $string ) {
foreach ( hametuha_punctuate( $string ) as $token ) {
printf( '<span class="token">%s</span>', $token );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment