PHP: formattare il testo di un tweet senza usare le espressioni regolari

PHP: formattare il testo di un tweet senza usare le espressioni regolari

Solitamente per formattare il testo di un tweet ottenuto tramite le API di Twitter si utilizzano le espressioni regolari PHP. In realtà esiste una soluzione migliore.

La soluzione consiste nell'usare le proprietà dell'oggetto tweet restituito dalle API:


function format_tweet( $tweet ) {
	$tweet_text = $tweet->text;
 
	
	$tweet_entities = array();
 
	
	foreach( $tweet->entities->urls as $url ) {
		$tweet_entities[] = array (
				'type'    => 'url',
				'curText' => substr( $tweet_text, $url->indices[0], ( $url->indices[1] - $url->indices[0] ) ),
				'newText' => '<a href="' . $url->expanded_url . '">' . $url->display_url . '</a>'
			);
	}  
 
	
	foreach ( $tweet->entities->user_mentions as $mention ) {
		$string = substr( $tweet_text, $mention->indices[0], ( $mention->indices[1] - $mention->indices[0] ) );
		$tweet_entities[] = array (
				'type'    => 'mention',
				'curText' => substr( $tweet_text, $mention->indices[0], ( $mention->indices[1] - $mention->indices[0] ) ),
				'newText' => '<a href="https://twitter.com/' . $mention->screen_name . '">' . $string . '</a>'
			);
	}
 
	
	foreach ( $tweet->entities->hashtags as $tag ) {
		$string = substr( $tweet_text, $tag->indices[0], ( $tag->indices[1] - $tag->indices[0] ) );
		$tweet_entities[] = array (
				'type'    => 'hashtag',
				'curText' => substr( $tweet_text, $tag->indices[0], ( $tag->indices[1] - $tag->indices[0] ) ),
				'newText' => '<a href="https://twitter.com/search?q=%23' . $tag->text . '&amp;src=hash">' . $string . '</a>'
			);
	}
 
	
	foreach ( $tweet_entities as $entity ) {
		$tweet_text = str_replace( $entity['curText'], $entity['newText'], $tweet_text );
	}
 
	return $tweet_text;
}

Esempio d'uso:


$tweets = json_decode( $data );

foreach( $tweets as $tweet ) {
	$formatted_tweet = format_tweet( $tweet );	
}

Torna su