Reputation: 714
The code:
$row['text'] = 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt';
if(preg_match_all('|http:\/\/t.co\/.{1,8}|i',$row['text'],$matches)){
foreach($matches[0] as $value){
$headers = get_headers($value,1);
if(is_array($headers['Location'])){
$headers['Location'] = $headers['Location'][0];
}
$row['text'] = preg_replace('|http:\/\/t.co\/.{1,8}|i', '<a href="' . $headers['Location'] . '">' . $headers['Location'] . '</a>',$row['text']);
}
}
This is related to get_headers()
. Sometimes get_headers($url,1)
returns an array with a location index key like so: [Location]=>Array([0]=>url1 [1]=>url2)
. I basically want to make [Location]
equal to [Location][0]
if [Location][0]
exists. However, the above code doesn't seem to accomplish that task. I've also tried array_key_exists()
and isset()
but neither solved the problem. Thoughts?
Upvotes: 1
Views: 112
Reputation: 175017
Don't try to replace on the fly. First get all the values, and then do the replace in one batch (using two arrays as the $search
and $replace
parameters).
<?php
$replace = array();
$row = array('text' => 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt');
if (preg_match_all('|http:\/\/t.co\/.{1,8}|i', $row['text'], $search)) {
foreach ($search[0] as $value) {
$headers = get_headers($value, 1);
if (is_array($headers['Location'])) {
$headers['Location'] = $headers['Location'][0];
}
$replace[] = "<a href='{$headers["Location"]}'>{$headers["Location"]}</a>";
}
$row['text'] = str_replace($search[0], $replace, $row['text']);
echo $row["text"];
}
P.S. - Next time, please tell us the context of your problem, tell us you "are making a service that resolves shortened URLs", don't let me figure that out from your code alone.
Upvotes: 2