WordPressからlet's punctuateを利用するgist
This file contains 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 | |
/** | |
* 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