JSON解码数组与preg_replace在PHP为推特推文



我有以下PHP代码来创建一个Twitter时间轴与可点击的链接:

if ($this->tweets === null) {
$this->tweets = self::$connection->get($type, ['count' => $count, "exclude_replies" => $er, "tweet_mode" => 'extended', "screen_name" => $screenname]);
$this->tweets = json_decode(json_encode($this->tweets), true);
$twitterCache->set($cachename, $this->tweets, option('twit.cachelife'));
}
public function setLinks($source) {
array_walk_recursive(
$source,
function (&$value, $key) {
if (in_array($key, array('url','text','full_text','expanded_url','description','display_url'), true ) ) {
if (!is_array($value)) {
$value = $this->linkify($value);
}
}
}
);
return $source;
}

public function linkify($value, $protocols = array('http', 'https', 'twitter', 'mail'), array $attributes = array('target' => '_blank'))
{
// Link attributes
$attr = '';
foreach ($attributes as $key => $val) {
$attr = ' ' . $key . '="' . htmlentities($val) . '"';
}
$links = array();
// Extract existing links and tags
$value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value);
// Extract text links for each protocol
foreach ((array)$protocols as $protocol) {
switch ($protocol) {
case 'http':
case 'https':   $value = preg_replace_callback('~(?:(https?)://([^s<]+)|(www.[^s<]+?.[^s<]+))(?<![.,:])~i', function ($match) use ($protocol, &$links, $attr) { if ($match[1]) $protocol = $match[1]; $link = $match[2] ?: $match[3]; return '<' . array_push($links, "<a $attr href="$protocol://$link">$link</a>") . '>'; }, $value); break;
case 'mail':    $value = preg_replace_callback('~([^s<]+?@[^s<]+?.[^s<]+)(?<![.,:])~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href="mailto:{$match[1]}">{$match[1]}</a>") . '>'; }, $value); break;
case 'twitter': $value = preg_replace_callback('~(?<!w)[@#](w++)~', function ($match) use (&$links, $attr) { return '<' . array_push($links, "<a $attr href="https://twitter.com/" . ($match[0][0] == '@' ? '' : 'search/%23') . $match[1]  . "">{$match[0]}</a>") . '>'; }, $value); break;
default:        $value = preg_replace_callback('~' . preg_quote($protocol, '~') . '://([^s<]+?)(?<![.,:])~i', function ($match) use ($protocol, &$links, $attr) { return '<' . array_push($links, "<a $attr href="$protocol://{$match[1]}">{$match[1]}</a>") . '>'; }, $value); break;
}
}
// Insert all link
return preg_replace_callback('/<(d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value);
}

书面文本正确解码为可读的内容,即使对于变音符或其他非英语字符,但标签(链接)与每个特殊字符断开,我想知道如何解决它。

需要使用addslashes()函数转义特殊字符

最新更新