Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's an edge case but the use of str_replace() in Styledev's answer could cause issues if one entity is contained within another. For example, "I'm a genius! #me #mensa" could become "I'm a genius! <a href="http://example.com" rel="nofollow">#me</a> <a href="http://example.com" rel="nofollow">#me</a>nsa" if the shorter entity is substituted first.</p> <p>This solution avoids that problem:</p> <pre><code>&lt;?php /** * Hyperlinks hashtags, twitter names, and urls within the text of a tweet * * @param object $apiResponseTweetObject A json_decoded() one of these: https://dev.twitter.com/docs/platform-objects/tweets * @return string The tweet's text with hyperlinks added */ function linkEntitiesWithinText($apiResponseTweetObject) { // Convert tweet text to array of one-character strings // $characters = str_split($apiResponseTweetObject-&gt;text); $characters = preg_split('//u', $apiResponseTweetObject-&gt;text, null, PREG_SPLIT_NO_EMPTY); // Insert starting and closing link tags at indices... // ... for @user_mentions foreach ($apiResponseTweetObject-&gt;entities-&gt;user_mentions as $entity) { $link = "https://twitter.com/" . $entity-&gt;screen_name; $characters[$entity-&gt;indices[0]] = "&lt;a href=\"$link\"&gt;" . $characters[$entity-&gt;indices[0]]; $characters[$entity-&gt;indices[1] - 1] .= "&lt;/a&gt;"; } // ... for #hashtags foreach ($apiResponseTweetObject-&gt;entities-&gt;hashtags as $entity) { $link = "https://twitter.com/search?q=%23" . $entity-&gt;text; $characters[$entity-&gt;indices[0]] = "&lt;a href=\"$link\"&gt;" . $characters[$entity-&gt;indices[0]]; $characters[$entity-&gt;indices[1] - 1] .= "&lt;/a&gt;"; } // ... for http://urls foreach ($apiResponseTweetObject-&gt;entities-&gt;urls as $entity) { $link = $entity-&gt;expanded_url; $characters[$entity-&gt;indices[0]] = "&lt;a href=\"$link\"&gt;" . $characters[$entity-&gt;indices[0]]; $characters[$entity-&gt;indices[1] - 1] .= "&lt;/a&gt;"; } // ... for media foreach ($apiResponseTweetObject-&gt;entities-&gt;media as $entity) { $link = $entity-&gt;expanded_url; $characters[$entity-&gt;indices[0]] = "&lt;a href=\"$link\"&gt;" . $characters[$entity-&gt;indices[0]]; $characters[$entity-&gt;indices[1] - 1] .= "&lt;/a&gt;"; } // Convert array back to string return implode('', $characters); } ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload