2

以下のコードブロックをまとめて、Twitterアカウントから自分のWebサイトに最新のツイートを表示できるようにしました。ただし、正しく機能していません。この最後の少しをデバッグするのを手伝っていただけませんか。Twitterのユーザー名とを使用して実行しているリンクをリンクタグで囲んだHTMLに変換するPHPを探していますpreg_replace

このスクリプトをテストすると、ツイート内の標準リンクをレンダリングするときに問題が発生することがわかります。このスクリプトでは、終了後の<a>タグが早すぎaます。これは修正が比較的簡単で、おそらく文字などをエスケープすることについてだと思います。

私のメインコードブロック:

    <?php
        /** Script to pull in the latest tweet */
        $username='benpaton';
        $format = 'json';
        $tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
        $latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
        $latestTweet = preg_replace('/http:\/\/([[a-z0-9_\.\-\+\&\!\#\~\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
        $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
        echo $latestTweet;
    ?>
4

3 に答える 3

6

正規表現を次のように変更します。

$latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);

これは私のために働いた。

完全なコード

<?php
    /** Script to pull in the latest tweet */
    $username='benpaton';
    $format = 'json';
    $tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
    $latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
    $latestTweet = preg_replace('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
    $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
    echo $latestTweet;
?>
于 2010-11-27T02:16:50.520 に答える
0

すべてのコードがバグがあるか不完全です!あなたがしたいことは次のようなものです:

$tweets[$i]['text_html'] = htmlspecialchars($tweet['text']);
$tweets[$i]['text_html'] = preg_replace('%(http://([a-z0-9_.+&!#~/,\-]+))%i','<a href="http://$2">$1</a>',$tweets[$i]['text_html']);
$tweets[$i]['text_html'] = preg_replace('/@([a-z0-9_]+)/i','<a href="http://twitter.com/$1">@$1</a>',$tweets[$i]['text_html']);
于 2011-01-17T16:32:27.890 に答える
0

これを試して:

<?php
/** Script to pull in the latest tweet */
$username='benpaton';
$format = 'json';
$tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
$latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
$latestTweet = preg_replace('%http://[a-z0-9_.+&!#~/,\-]+%', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet);
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
echo $latestTweet;
?>
于 2010-11-27T02:56:53.880 に答える